-2

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].

W2a
  • 736
  • 2
  • 9
  • 23
  • Mainly because the standard says so. For a more technical reasons, some `malloc()` implementations put bookkeeping data right before the allocated memory region. Passing something else than the pointer `malloc()` gave you to `free()` would cause `free()` to interpret garbage data as its bookkeeping data with fatal consequences. – fuz Nov 28 '15 at 16:02
  • Thank you, I get it now. – W2a Nov 28 '15 at 19:12

2 Answers2

2

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.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

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.

Malloc

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 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.

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.

Antoine Pietri
  • 793
  • 1
  • 10
  • 25