C programming malloc stdlib.h

In C programming the <stdlib.h> malloc function allocate memory in heap.This means the memory is allocated during runt-time.The declaration of the function is shown below.

Link: what is run-time?

void *malloc(size_t size);

size_t -The number of bytes the memory is to be allocated.

Return type
void* -A pointer to the memory allocated.

Some points to note:

i) The memory allocated is ‘void’ type.To use the memory for other data type cast the memory to the respective type.

ii)If the argument passed is 0 or the size requested is 0 the behavior is implementation-defined.In this case the function will either return a NULL pointer or it behave as thought the size is non-zero.

iii) If the allocation of the memory failed NULL is returned.

Note whenever malloc or calloc or realloc is call do not forget to call the ‘free’ function to deallocate the storage.

Link :C free stdlib.h

Code example

char *cmem=(char*)malloc( 5 ); //allocate memory to store 5 characters

void *vmem=malloc( 0 ); //behavior implementation-defined


A more exhaustive code example is given below.

Code example

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

int main( )
char c[]=”New string” ;

char *cmem=(char*)malloc( strlen(c)+1 ); //plus 1 for the last ‘\0’ character

if( cmem!=NULL) //check if the memory was allocated
size_t len=0 ;

 while( len<strlen( c ) )
 printf( “%c” , *(cmem+len) ); //accessing the characters stored in the memory pointed by ‘cmem’ one by one
 len++ ;

free( cmem ); //do not forget!!

getchar( );
return 0;

Output in Visual Studio,

New string

Related links

->C calloc stdlib.h

->C realloc stdlib.h