My question is very simple one. Say we have:
char* ptr = (char*) malloc(sizeof(char)*SIZE);
ptr+= SIZE/2;
free(ptr);
What happens when we free the pointer? Is it undefined operation?
Does it free all of SIZE buffer or only the remaining SIZE/2?
Thanks in advance for disambiguating this for me.
Your program will probably crash: the free() operation is actually quite simple in C, but works only on the original allocated address.
The typical memory allocator works like this pseudo code:
So when you call
free(ptr), the allocator goes 6 bytes before your pointer to check for the signature. If it doesn’t find the signature, it crashes 🙂