How can I correctly handle malloc failure in C, especially when there is more than one malloc?

前端 未结 6 570
我在风中等你
我在风中等你 2021-02-01 02:49

Suppose this is a part of my code:

 int foo()
 {  
    char *p, *q ;
    if((p = malloc(BUFSIZ)) == NULL) {
        return ERROR_CODE;
    }
    if((q = malloc(B         


        
6条回答
  •  清酒与你
    2021-02-01 03:26

    it is matter of habit, but I prefer:

    int returnFlag = FAILURE;
    
    if ((p = malloc...) != NULL)
    {
        if ((q = malloc..) != NULL)
        {
            // do some work
            returnFlag = SUCCESS; // success only if it is actually success
    
            free(q);
        }
        free(p);
    }
    
    return returnFlag; // all other variants are failure
    

提交回复
热议问题