The free() function is defined in the stdlib.h header file. It helps to deallocate or free up the dynamically allocated memory using calloc, malloc, or realloc.
void free(void *ptr); #where ptr is a memory pointer
The free() function takes a single parameter. If the ptr passed is a null pointer nothing is happend.
Parameter | Description | Required / Optional |
---|---|---|
ptr | pointer to a memory block previously allocated and need to be deallocated | Required |
The free() function does not return any value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *s;
/*memory allocation */
s = (char *) malloc(12);
strcpy(s, "programming");
printf("String = %s, Address = %u\n", s, s);
/* Reallocating memory */
s = (char *) realloc(s, 20);
strcat(s, ".com");
printf("String = %s, Address = %u\n", s, s);
free(s);
return(0);
}
Output:
String = programming, Address = 355090448 String = programming.com, Address = 355090448
#include <stdio.h>
#include <stdlib.h>
int main (){
int k, * pt, t = 0;
pt = calloc(10, sizeof(int));
if (pt == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Sequence sum of the first 10 terms \ n ");
for (k = 0; k < 10; ++k) { * (pt + k) = k;
sum += * (pt + k);
}
printf("Sum = %d", t);
free(pt);
return 0;
}
Output:
Sequence sum of the first 10 terms Sum = 45