【问题标题】:Solving C warning - dereferencing a null pointer解决 C 警告 - 取消引用空指针
【发布时间】:2021-03-21 16:50:35
【问题描述】:

这是来自 facebook infer 的错误报告。

error: NULL_DEREFERENCE
  pointer `stack` last assigned on line 24 could be null and is dereferenced at line 25, column 5.
  22. struct string_stack* create_String_Stack(unsigned capacity)
  23.   {
  24.       struct char_stack* stack = calloc(1,sizeof(struct char_stack));
  25. >     stack-> capacity = capacity;
  26.       stack->top = -1;
  27.       stack->array = (char*)malloc(stack->capacity * sizeof(char));
struct char_stack
{
    int top;
    unsigned capacity;
    char* array;
};

如何摆脱这个警告?

【问题讨论】:

  • 查看calloc的结果? if(stack == NULL) { /* handle error & terminate */ }.
  • 警告是 100% 正确的。 calloc 可以返回 NULL 而你不检查这个。

标签: c pointers null dereference


【解决方案1】:

我相信问题出在struct char_stack* stack = calloc(1,sizeof(struct char_stack));。如果您只是简单地说struct char_stack* stack= malloc(sizeof(struct char_stack);,因为您只想要一件物品来节省空间,那么我相信它可能会解决它。如果没有,那么我建议检查您是否正确发音 sizeof(struct char_stack)。最后,您必须始终检查if (stack==NULL) ,因为程序可能找不到空间来为指针分配空间。另外,我建议使用 typedef struct char_stack Char_stack;,这样你就不需要一直写struct char_stack ,而只需要写 Char_stack。我希望这可以帮助您找到问题。

【讨论】:

  • 我在使用 malloc 时仍然收到此错误。但是如果每次都检查null,代码中的分支会太多。还是谢谢!
  • 每次分配只需要检查一次。如果您不想使用 'if',请使用 try {..}catch{..} 块
  • @gobinda 要使用try {...} catch {...},OP 需要使用不同的编程语言。
  • 使用不同大小的内存分配不能解决问题。 malloc 仍然可以返回 NULL 必须检查。
猜你喜欢
  • 1970-01-01
  • 2010-09-22
  • 2011-06-27
  • 1970-01-01
  • 2014-06-01
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
  • 2015-01-13
相关资源
最近更新 更多