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

C examples for Memory:malloc

Introduction

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"); 
   else 
      printf("\nMemory allocated.\n"); 
}

Result


Related Tutorials