Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c - Should I check if malloc() was successful?

Should one check after each malloc() if it was successful? Is it at all possible that a malloc() fails? What happens then?

At school we were told that we should check, i.e.:

arr = (int) malloc(sizeof(int)*x*y);
if(arr==NULL){
    printf("Error. Allocation was unsuccessful. 
");
    return 1;
}

What is the practice regarding this? Can I do it this way:

if(!(arr = (int) malloc(sizeof(int)*x*y))
    <error>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This mainly only adds to the existing answer but I understand where you are coming from, if you do a lot of memory allocation your code ends up looking very ugly with all the error checks for malloc.

Personally I often get around this using a small malloc wrapper which will never fail. Unless your software is a resilient, safety critical system you cannot meaningfully work around malloc failing anyway so I would suggest something like this:

static inline void *MallocOrDie(size_t MemSize)
{
    void *AllocMem = malloc(MemSize);
    /* Some implementations return null on a 0 length alloc,
     * we may as well allow this as it increases compatibility
     * with very few side effects */
    if(!AllocMem && MemSize)
    {
        printf("Could not allocate memory!");
        exit(-1);
    }
    return AllocMem;
}

Which will at least ensure you get an error message and clean crash, and avoids all the bulk of the error checking code.

For a more generic solution for functions that can fail I also tend to implement a simple macrosuch as this:

#define PrintDie(...) 
    do 
    { 
    fprintf(stderr, __VA_ARGS__); 
    abort(); 
    } while(0)

Which then allows you to run a function as:

if(-1 == foo()) PrintDie("Oh no");

Which gives you a one liner, again avoiding the bulk while enabling proper checks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...