Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I free() by referencing an offset pointer? [duplicate]

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.

like image 838
soulseekah Avatar asked Dec 28 '22 02:12

soulseekah


2 Answers

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.

like image 86
Tony Delroy Avatar answered Jan 30 '23 08:01

Tony Delroy


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.

like image 39
Naveen Avatar answered Jan 30 '23 09:01

Naveen