From cplusplus.com:
A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.
If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.
If ptr is a null pointer, the function does nothing.
Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location.
But what happen if my pointer doesn't point to the start of the block.
For example:
int *ptr = malloc(sizeof(int)*10);
ptr++;
free(ptr);
Does free only free the last 9 positions? This would be horrible in this case, then:
int *ptr = malloc(sizeof(int)*10);
int i;
for(i=0; i<10; i++, ptr++);
free(ptr);
Here ptr points outside of the block of memory reserved by malloc.
And what would be the behaviour of this?
int *ptr1 = malloc(sizeof(int)*10);
int *ptr2 = ptr1 + 2;
free(ptr2);
Thanks.