-1

My understanding is that if char *my_word is allocated ONE byte of memory malloc(1), then technically, then the following code would produce an out-of-bounds error

char *my_word = malloc(1);

my_word[0] = 'y';
my_word[1] = 'e';
my_word[2] = 's';

and yet, the code runs just fine and doesn't produce any error. In fact, printf("%s", my_word) prints the word just fine.

Why is this not producing an out-of-bounds error if I specifically only allocated 1 byte of memory?

Jules
  • 423
  • 3
  • 11

3 Answers3

1

C doesn't have explicit bounds checking. That's part of what makes it fast. But when you write past the bounds of allocated memory, you invoke undefined behavior.

Once you invoke undefined behavior, you can't reliable predict what the program will do. It may crash, it may output strange results, or (as in this case) it may appear to work properly. Additionally, making a seemingly unrelated change such as adding a printf call for debugging or adding an unused local variable can change how undefined behavior manifests itself.

Just because the program could crash doesn't mean it will.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

This comes down to the system it is running on. Generally a malloc will allocate in multiples of a certain block size. Eg the block size maybe 16 bytes on your system and malloc will allocate 16 even though you only asked for 1. So in this case you are getting away with overflowing the buffer because you are not writing on memory that is used by anything else. However you should never rely on this. Always assume that when you write outside the amount requested that bad things will happen. C does not provide any built-in mechanism to protect you from buffer overflowing, it is up to you to know the size of your buffers and ensure that you never read/write outside of them.

For example if you allocated a buffer a multiple of the block size then writing to the next byte will probably start overwriting critical memory control blocks which may show up as bizarre errors later when you try to free or allocate more memory.

waterjuice
  • 829
  • 5
  • 14
  • An OS error will generally only occur when you read/write to unallocated memory, however C usually allocates a bunch of pages then manages its own smaller allocations within that, so the chances are a small overwrite/overread won't actually venture into unallocated system memory, and instead just somewhere where there is real memory. There are tools such as Valgrind (https://valgrind.org) which specifically find this kind of bug. – waterjuice Dec 13 '19 at 03:20
0

C does not performs bound check. It is just undefined behavior when you access out of bounds which means it can work as normal.

openingnow
  • 134
  • 10