C programming stdlib.h function - void free(void *ptr)
The free
function is a memory deallocation function in the C standard library that is used to free the memory previously allocated by the malloc
, calloc
, or realloc
functions. The syntax of the free
function is as follows:
void free(void *ptr);
The ptr
argument is a pointer to the memory block that was previously allocated using malloc
, calloc
, or realloc
.
When you call free
, the memory block pointed to by ptr
is deallocated, which means that the system may reclaim the memory and use it for other purposes. It is important to note that the free
function does not change the value of the pointer variable ptr
itself. After calling free
, ptr
still points to the same address in memory, but the memory block that it points to is no longer allocated.
It is important to call free
for every memory block that you allocate using malloc
, calloc
, or realloc
to avoid memory leaks, which occur when you allocate memory but do not release it when you are done using it. Here is an example that demonstrates how to use the free
function:
#include <stdio.h> #include <stdlib.h> int main(void) { int *ptr = (int *)malloc(10 * sizeof(int)); if (ptr == NULL) { printf("Memory allocation failed\n"); return 1; } for (int i = 0; i < 10; i++) { ptr[i] = i; } for (int i = 0; i < 10; i++) { printf("%d ", ptr[i]); } printf("\n"); free(ptr); return 0; }
In this example, the malloc
function is used to allocate memory for an array of 10 int
elements. The size of each element is sizeof(int)
. The program then uses a for
loop to fill the array with values, and another for
loop to print out the elements of the array. Finally, the free
function is called to deallocate the memory block pointed to by ptr
. Note that free
should be called after you are done using the allocated memory block. If you access the memory block after calling free
, you may get unexpected results or cause a segmentation fault.