Deallocate (free) Memory
When you no longer need a block of memory you should deallocate it. Deallocation is also referred to as "freeing" the memory.
Dynamic memory stays reserved until it is deallocated or until the program ends.
Once the memory is deallocated it can be used by other programs or it may even be allocated to another part of your program.
Free Memory
To deallocate memory, use the free() function:
free(pointer);
The pointer parameter is a pointer to the address of the memory to be deallocated:
int *ptr;
ptr = malloc(sizeof(*ptr));
free(ptr);
ptr = NULL;
Note: It is considered a good practice to set a pointer to
NULLafter freeing memory so that you cannot accidentally continue using it. If you continue using memory after it has been freed you may corrupt data from other programs or even another part of your own program.
Example
int *ptr;
ptr = malloc(sizeof(*ptr)); // Allocate memory for one integer
// If memory cannot be allocated, print a message and end the main()
function
if (ptr == NULL) {
printf("Unable to allocate memory");
return 1; //
Exit the program with an error code
}
// Set the value of the integer
*ptr = 20;
// Print the
integer value
printf("Integer value: %d\n", *ptr);
// Free allocated memory
free(ptr);
// Set the pointer to
NULL to prevent it from being accidentally used
ptr = NULL;
Memory Leaks
A memory leak happens when dynamic memory is allocated but never freed.
If a memory leak happens in a loop or in a function that is called frequently it could take up too much memory and cause the computer to slow down.
There is a risk of a memory leak if a pointer to dynamic memory is lost before the memory can be freed. This can happen accidentally, so it is important to be careful and keep track of pointers to dynamic memory.
Here are some examples of how a pointer to dynamic memory may be lost.
Example 1
int x = 5;
int *ptr;
ptr = calloc(2, sizeof(*ptr));
ptr = &x;
Example 2
void myFunction() {
int *ptr;
ptr = malloc(sizeof(*ptr));
}
int main() {
myFunction();
printf("The function has
ended");
return 0;
}
Example 3
int* ptr;
ptr = malloc(sizeof(*ptr));
ptr = realloc(ptr,
2*sizeof(*ptr));
Summary
In summary, when managing memory in C, use best practices:
- Remember to check for errors (
NULLreturn values) to find out if memory allocation was sucessful or not - Prevent memory leaks - always remember to free memory that is no longer used, or else the program might underperform or even worse, crash if it runs out of memory
- Set the pointer to
NULLafter freeing memory so that you cannot accidentally continue using it
Tip: You will learn more about NULL in our NULL chapter.