为什么我会收到此警告?

问题描述 投票:0回答:1

“realloc”可能返回空指针:将空指针分配给“parameter-name”,并将其作为参数传递给“realloc”,将导致原始内存块泄漏。

我在使用 realloc 的两行上收到上述警告,有人知道我在这里做错了什么吗? 这是代码:

if (sequenceLength == size)
{
   size *= 2;
   sequence=realloc(sequence, size);        
   if (sequence == NULL)
   {
      printf("reallocation was unsuccessful.");
      free(sequence);
      free(playerInput);
      exit(EXIT_SUCCESS);
   }

   playerInput=realloc(playerInput, size);
   if (playerInput == NULL)
   {
        printf("reallocation was unsuccessful.");
        free(sequence);
        free(playerInput);
        exit(EXIT_SUCCESS);
    }
}

我尝试在网上搜索但找不到任何东西。

c warnings
1个回答
0
投票

正如警告所述,如果将

realloc
的返回值直接分配回要重新分配的指针并且调用失败,则现在会出现内存泄漏,因为指向原始内存块的指针丢失了。如果
realloc
失败,原来的内存块仍然有效。

需要将结果赋值给临时变量,只有成功后才将其赋值回来。

   void *tmp=realloc(sequence, size);        
   if (tmp == NULL)
   {
      printf("reallocation was unsuccessful.");
      free(sequence);
      free(playerInput);
      exit(EXIT_SUCCESS);
   }
   sequence = tmp;
© www.soinside.com 2019 - 2024. All rights reserved.