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

前端 未结 6 581
我在风中等你
我在风中等你 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:42

    I think the first answer is the most general purpose as it can be used for errors other than those caused by malloc. However I would remove the gotos and use a single pass while loop like so.

    int foo()
    {
      char *p = NULL;
      char *q = NULL;
      int ret = 0;
      do {
        if (NULL == (p = malloc(BUFSIZ)))
        {
          ret = ERROR_CODE;
          break;
        }
    
        // possibly do something here
    
        if (NULL == (q = malloc(BUFSIZ)))
        {
          ret = ERROR_CODE;
          break;
        }
    
        // insert similar repetitions
    
        // hopefully do something here
      } while(0);
      free (p);
      free (q);
      return ret;
    }
    

提交回复
热议问题