Check that malloc() was successful before attempting to use the memory. - C Memory

C examples for Memory:malloc


To test the malloc() function's outcome, simply use an if condition to test for a NULL pointer.

Demo Code

#include <stdio.h> 
#include <stdlib.h> 
int main()//from  w  ww  .j a  v  a  2 s. c  om
   char *name; 
   name = (char *) malloc(80 * sizeof(char)); 
   if ( name == NULL ) 
      printf("\nOut of memory!\n"); 
      printf("\nMemory allocated.\n"); 


Related Tutorials