malloc & Free Function
malloc & Free Function
int main() {
int *numbers; // Declare a pointer to int
int n = 5; // Number of integers to allocate space for
if (numbers == NULL) {
printf("Memory allocation failed\n");
return 1;
}
return 0;
}
In this example, memory is allocated for an array of integers using malloc(), the
array is populated with values, and then the allocated memory is freed using the
free() function to prevent memory leaks.
Free Function
The free function is a standard library function in C that is used to deallocate
memory that was previously allocated using functions like malloc, calloc, or
realloc. When you allocate memory dynamically using these functions, the
operating system reserves a block of memory for your program to use.
However, when you're done using that memory, it's important to release it
back to the system using the free function. This prevents memory leaks,
which can lead to inefficient memory usage and performance issues over
time.
Here's a simple explanation of how the free function works:
1. Memory Allocation: When you use functions like malloc to allocate
memory, the operating system sets aside a block of memory for your
program and returns a pointer to the beginning of that block.
2. Memory Usage: You use the allocated memory to store data, such as
integers, characters, arrays, or complex structures. This memory remains
allocated until you explicitly release it using the free function.
3. Memory Deallocation: When you're done using the memory and no longer
need the data stored in it, you call the free function, passing the pointer to
the beginning of the allocated memory as an argument.
4. Memory Release: The free function marks the previously allocated memory
block as available for reuse. The operating system can then use this memory
for other purposes, and your program should no longer access or modify the
memory that was freed.
Here's an example demonstrating the usage of the free function:
#include <stdio.h>
#include <stdlib.h>
int main() {
int* intPtr = (int*)malloc(sizeof(int));
*intPtr = 42;
// Now, intPtr should not be used since the memory it points to has been freed
return 0;
}