The free function signature
What you'll learn: How to tell the computer you are finished with a block of heap memory using the free function.
The returning library book
Think of memory allocation like checking out a book from a library. When you use malloc, the computer hands you a "book" (a block of memory) and gives you a library card (a pointer) to track where it is. If you just keep the books forever, the library eventually runs out of space for everyone else.
In C, this is called a memory leak. To prevent this, you must use the free function to "return" the memory to the system once you are done using it.
The signature
The signature for the free function is found in the <stdlib.h> header:
void free(void *ptr);
Let's break down what this tells us:
- void: The function returns nothing. Once you give the memory back, the transaction is over.
- free: The name of the function.
- *void ptr: This is the most important part. It accepts a pointer to the memory block you want to release. Because it is a
voidpointer, it doesn't care if you were storing integers, characters, or complex structures; it just needs the starting address of the block you originally received frommalloc.
How to use it
When you call free, you must pass the exact address that was returned by your allocation function. You cannot pass a pointer to the middle of the block, nor can you pass a pointer that has already been freed.
#include <stdlib.h>
int main() {
// 1. Request memory for one integer
int *my_number = malloc(sizeof(int));
if (my_number != NULL) {
*my_number = 42; // Use the memory
// 2. We are done! Return it to the system
free(my_number);
// 3. Good practice: set the pointer to NULL
// so we don't accidentally use it again.
my_number = NULL;
}
return 0;
}
Notice that free does not "delete" the pointer variable itself; it simply tells the operating system that the memory located at that address is now available for other programs to use.
Key takeaway
The free function takes the pointer returned by malloc and releases that memory back to the system to prevent memory leaks.