C programming free stdlib.h


In C programming the <stdlib.h> free function frees the memory allocated in heap.The declaration of the function is shown below.

void free(void *ptr);

Parameters:
void* -A pointer to the memory allocated in heap.

Return type
void

Some points to note:

i) You must always call this function whenever you have called the calloc , malloc or realloc functions.Those functions allocate memory in heap and only the ‘free’ function can deallocate them.Forgetting to call the ‘free’ function will produce memory leakage in your program.

ii) If the ‘ptr’ points to NULL nothing happens.

iii) If the memory has been freed and we try to delete it again,in such case the behavior is undefined.

Link : C calloc stdlib.h

Code example

void *mem=calloc( 3 , sizeof(char) );

void imem=malloc( sizeof(int)*4 ); //allcoate memory that can hold 4 integers

free(mem);
free(imem);





A more exhaustive code example using ‘free’ function is given below.

Code example

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main( )
{
char c[]=”Name” ;

char *cmem=(char*)malloc( strlen(c)+1 );

void *vmem=malloc(0);

memcpy(cmem, c , strlen(c) + 1); //copying the content of ‘c’ string to memory pointed by cmem

printf(“\n%c %c %c %c “, *((char*)cmem), *(((char*)cmem) + 1) ,
*(((char*)cmem) + 2) , *(((char*)cmem) + 3) );

free(cmem);
free(vmem); //work fine

free(cmem); //behavior undefined

getchar( );
return 0;
}

Output,

N a m e

Deleting the memory pointed to by ‘cmem’ for the second time will produce undefined behavior,in Visual Studio you will get “Debug assertion failed” error message.