Should we check if memory allocations fail?

后端 未结 7 1849
温柔的废话
温柔的废话 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:07

    Always check the return value, but for clarity, it's common to wrap malloc() in a function which never returns NULL:

    void *
    emalloc(size_t amt){
        void *v = malloc(amt);  
        if(!v){
            fprintf(stderr, "out of mem\n");
            exit(EXIT_FAILURE);
        }
        return v;
    }
    

    Then, later you can use

    char *foo = emalloc(56);
    foo[12] = 'A';
    

    With no guilty conscience.

提交回复
热议问题