Search code examples
cfunctionmemory-managementfreerealloc

If free() is called inside a function, does it only free locally?


Still learning the ropes of allocation and deallocation and I'm curious about something.

Let's say you allocate memory for an array:

int *array = malloc(5 * sizeof(int));

You send the array to a function and reallocate it there. The function parameter would have to be a double pointer to the array (or &array) or the reallocation would only take place locally.

If you also want to free (deallocate) the array inside another function, does it also have to be a double pointer? Would freeing in a function only happen locally? If not, how does it differ from reallocation in that aspect?


Solution

  • No, free() frees the memory globally, just as malloc() allocates the memory globally. That is, the memory is allocated and, provided the pointer to it is made accessible (function argument, function return value, global variable), it stays allocated and accessible indefinitely — until freed or the program exits (or it is leaked; there's no longer a valid accessible pointer to the memory). And allocated memory that is freed is freed indefinitely. It might be made available again by another allocation, but that's coincidental.

    If you pass a pointer to allocated memory into a function and that function frees it, it is freed for the calling code. The calling code needs to know that the called function freed the memory so it doesn't try to use the memory after it was freed.