how to free memory in c
To free memory in C, you need to use the free()
function. Here are the steps to follow:
- Allocate memory using the
malloc()
,calloc()
, orrealloc()
functions. These functions allocate memory dynamically on the heap. - When you are done using the allocated memory, call the
free()
function to release the memory back to the system.
Here is an example that demonstrates how to free memory in C:
#include <stdlib.h>
int main() {
// Allocate memory for an integer array
int numbers = malloc(5 sizeof(int));
// Check if the allocation was successful
if (numbers == NULL) {
// Handle allocation failure
return 1;
}
// Use the allocated memory
// Free the allocated memory
free(numbers);
return 0;
}
In this example, we allocate memory for an integer array using malloc()
and store the address of the allocated memory in the numbers
pointer. After using the allocated memory, we call free(numbers)
to release the memory.
It's important to note that you should only free memory that has been dynamically allocated using malloc()
, calloc()
, or realloc()
. Trying to free memory that has not been allocated dynamically or has already been freed can lead to undefined behavior.
I hope this explanation helps! Let me know if you have any further questions.