Search code examples
cvalgrindcalloc

What happens if I set a value outside of the memory allocated with calloc?


Consider the following:

int* x = calloc(3,sizeof(int));
x[3] = 100;

which is located inside of a function.

I get no error when I compile and run the program, but when I run it with valgrind I get an "Invalid write of size 4".

I understand that I am accessing a memory place outside of what I have allocated with calloc, but I'm trying to understand what actually happens.

Does some address in the stack(?) still have the value 100? Because there must certainly be more available memory than what I have allocated with calloc. Is the valgrind error more of a "Hey, you probably did not mean to do that"?


Solution

  • I understand that I am accessing a memory place outside of what I have allocated with calloc, but I'm trying to understand what actually happens.

    "What actually happens" is not well-defined; it depends entirely on what gets overwritten. As long as you don't overwrite anything important, your code will appear to run as expected.

    You could wind up corrupting other data that was allocated dynamically. You could wind up corrupting some bit of heap bookkeeping.

    The language does not enforce any kind of bounds-checking on array accesses, so if you read or write past the end of the array, there are no guarantees on what will happen.