简体   繁体   English

解决 C 警告 - 取消引用 null 指针

[英]Solving C warning - dereferencing a null pointer

This is the bug report from facebook infer.这是来自 facebook 推断的错误报告。

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;
};

How can get rid of this warning?如何摆脱这个警告?

I believe the problem is at struct char_stack* stack = calloc(1,sizeof(struct char_stack));我相信问题出在struct char_stack* stack = calloc(1,sizeof(struct char_stack)); . . If you just simply say struct char_stack* stack= malloc(sizeof(struct char_stack); as you want only 1 item to save space and then I believe that it probably solve it. If it does not then I would suggest checking if you correctly pronounce sizeof(struct char_stack).In the end, you always must check if (stack==NULL) because the program might not find a space to allocate space for the pointer. Also, I would recommend using typedef struct char_stack Char_stack; so you don't need to write all the time the struct char_stack but only Char_stack . I hope that this will help you to find the problem.如果你只是简单地说struct char_stack* stack= malloc(sizeof(struct char_stack);因为你只想要 1 个项目来节省空间,那么我相信它可能会解决它。如果没有,那么我建议检查你是否正确发音sizeof(struct char_stack)。最后,你总是必须检查if (stack==NULL)因为程序可能找不到空间来为指针分配空间。另外,我建议使用typedef struct char_stack Char_stack;所以你不要不需要一直写struct char_stack而只Char_stack 。我希望这能帮助你找到问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM