Let's say I have allocated a big enough char**
array.
Why can I do free(arr)
but not free(arr + 5)
?
Please notice that I'm not speaking about arr[0]
or arr[5]
.
Let's say I have allocated a big enough char**
array.
Why can I do free(arr)
but not free(arr + 5)
?
Please notice that I'm not speaking about arr[0]
or arr[5]
.
You always call free()
with the pointer that was returned by malloc()
, realloc()
or calloc()
. You must not pass any other pointers.
From the free()
manual:
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
malloc(3)
doesn't work that way. It allocates a fixed-size block of data in the memory, adds metadata at the start of the block (like the address of the next free block or the size of the block) and returns the address just after the metadata.
free(3)
needs the information contained in the metadata to be executed (for example, to update the addresses of the free blocks in its linked list. If you provide a pointer that has not been allocated by malloc(3)
, the metadata are not present and free
is unable to do that.
For that reason, the man page of free(3)
explicitely forbids to pass a pointer that has not been allocated by `malloc(3)
The
free()
function frees the memory space pointed to byptr
, which must have been returned by a previous call tomalloc()
,calloc()
, orrealloc()
. Otherwise, or iffree(ptr)
has already been called before, undefined behavior occurs. Ifptr
isNULL
, no operation is performed.
Doing so may result in undefined behavior, that, if your system has not put some protections in place to prevent you from doing so, could result in security breaches, since free(3)
will write on arbitrary memory zones pointed by the fake metadata.