Should we check if memory allocations fail?

后端 未结 7 1852
温柔的废话
温柔的废话 2020-12-31 08:41

I\'ve seen a lot of code that checks for NULL pointers whenever an allocation is made. This makes the code verbose, and if it\'s not done consistently, only when the program

相关标签:
7条回答
  • 2020-12-31 09:10

    Similar to Dave's approach above, but adds a macro that automatically passes the file name and line number to our allocation routine so that we can report that information in the event of a failure.

    #include <stdio.h>
    #include <stdlib.h>
    
    #define ZMALLOC(theSize) zmalloc(__FILE__, __LINE__, theSize)
    
    static void *zmalloc(const char *file, int line, int size)
    {
       void *ptr = malloc(size);
    
       if(!ptr)
       {
          printf("Could not allocate: %d bytes (%s:%d)\n", size, file, line);
          exit(1);
       }
    
       return(ptr);
    }
    
    int main()
    {
       /* -- Set 'forceFailure' to a non-zero value in order to observe
             how 'zmalloc' behaves when it cannot allocate the
             requested memory -- */
    
       int bytes        = 10 * sizeof(int);
       int forceFailure = 0;
       int *anArray     = NULL;
    
       if(forceFailure)
          bytes = -1;
    
       anArray = ZMALLOC(bytes);
    
       free(anArray);
    
       return(0);
    }
    
    0 讨论(0)
提交回复
热议问题