Possible Duplicate:
Does the pointer passed to free() have to point to beginning of the memory block, or can it point to the interior?
I'm allocating some memory on the heap using malloc()
. I'm adding an offset to the pointer and returning it to a calling function return ptr+(sizeof(char)*4))
, where this return value is stored in ptrReturned
, for example.
The big question is, when I free(ptrReturned)
, which is offset from the beginning of the allocated block by sizeof(char)*4
, will the whole block be freed or will it free memory from the offset up to the end of the allocated block? The compiler I'm using is MSVC++2008.
If the allocated addresses are stored in a linked list, and there are pointers to previous items, then it should free the whole block from where previous pointer is NULL up to where next pointer is NULL, right?
I've tried debugging and watching the memory, but I can't get it to overwrite the freed up block space. Is there a way to maybe explicitly try and allocate space on the heap at a defined address, and maybe get an exception from trying to allocate already allocated memory? That way I'll be able to know, if there is, of course, no simpler answer.
I hope the question is clear, if I'm missing on some information, please let me know in the comments. Thanks.
You must pass in the same pointer value to free() that was returned by malloc(), or your program will have undefined behaviour. Your expectation that it might free all or part of the allocated block is unfounded.
I found the following quote from the standard:
Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With