I have been told that even if it were safe it's definitely bad practice. My question is, is it actually safe to do this, or is it down-right undefined behavior? Suppose I have allocated a 100 byte chunk of memory, but I want to shrink it to 50. Would it be safe to add 50 to the pointer and free it? Here is an example in code:
char *ptr = malloc(100);
//...
free(ptr+50);
//Presumably, since I freed the second half only, would that be equivalent to ptr = realloc(ptr, 50);?
Is this cross-platform/undefined behavior? Is it safe to use this method of shrinking memory?
You can only pass to free
a pointer that was returned from malloc
, realloc
, calloc
. Passing anything else is undefined behavior.
Section 7.22.3.3p2 of the C standard regarding the free
function states:
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.
The proper thing to do here would be to allocate a fresh block of memory, use memcpy
to copy the bytes over, and free
the old block.