Dynamic arrays: using realloc() without memory leaks

后端 未结 2 1668
北恋
北恋 2020-12-19 08:58

I use realloc to resize the memory allocated:

char **get_channel_name(void)   
{
    char **result;
    int n;

    result = (char **) 0;
    for (elem = snd         


        
2条回答
  •  佛祖请我去吃肉
    2020-12-19 09:27

    If realloc() fails it returns NULL.

    So if you do (and assuming realloc() would fail)

    result = realloc(result, ...);
    

    result will be assigned NULL and what it pointed to is not free()ed and the address to be free()ed is lost.

    To fix this do:

    {
      void * tmp = realloc(result, ...);
      if (NULL == tmp)
      {
        /* Handle error case, propably freeing what result is pointing to. */
      }
      else
      {
        result = tmp;
      }
    }
    

提交回复
热议问题