Freeing pointer after pointer arithmetic
My question is very simple one. Say w开发者_C百科e 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:
- ask to alloc 64 bytes
- allocator allocs 70 bytes (6 bytes more)
- the first 2 bytes is set to a "signature", a pattern recognized by the allocator to identify the memory allocated by him
- the next 4 bytes denote the allocated size
- return a pointer to the start of the 7th byte
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 :)
If the argument to free()
does not match a pointer previously allocated by means of malloc()
and friends, the behaviour is undefined. You will most likely encounter a segmentation fault or a failed assertion in your version of libc
.
Offtopic: it's better you didn't cast the result of malloc()
in C.
The behavior is undefined and will most likely result in a segmentation fault - and that's the good case. In the worst case, it will corrupt your program's memory and induce all kind of weird bugs and wrong outputs.
On most implementations this should result in some sort of fatal error. You can only free the begining of an allocated buffer.
They typical error you would get on windows (with the visual studio compilers) would be something like "not a valid heap pointer". On linux, as said above by phihag, it would usually result in a segmentation fault. In both cases, it is a runtime error that would usually terminate the execution of the program.
The behaviour is undefined. I guess you'd get a segfault ... that's what I got when I tried in my system.
free()
requires the caller to pass an address that was returned by a memory allocator function like malloc()
. Anything else results in undefined behaviour.
精彩评论