c - 访问非空结构成员时出现段错误-

标签 c struct segmentation-fault bit-fields

<分区>

我收到段错误,同时将结构的成员与 0 进行比较。 令人困惑的部分是比较确实发生了几次,然后是暗恋。

请帮忙。 代码:

Dword addup(void)
{
  Symbol *curr=NULL;
  Dword ans=0;
  plast->next=NULL;

  if( (phead==NULL) || (plast==NULL) )/*checks that the global pointer to the head & tail is not null.*/
      return 0;

  curr=phead;

  printf("point 1 in addup()********\n");

  for( ; curr!=NULL ; curr=curr->next )
  {

      if(curr!=NULL)
      {

          if(  ((curr->feature.oper)==0)  &&  ((curr->feature.ext)==0)  )/*crash here !*/
          {
              puts("point 2AA in addup()********");

              curr->adess=+IC;
              ans++;
          }
          puts("point 2B in addup()********");
      }

      if((curr->next)==NULL)
          break;
  }


  if(  (curr!=NULL) && (plast!=NULL) )
  {
      if(curr==plast)/*meaning all the list been searched.*/
          return ans;
  }


  return (-1); }

和符号:

typedef struct snode  {
    char label[MAXLABEL];

    Dword adess;

    struct
    {
        unsigned int ext:1;
        unsigned int oper:1;
    }feature;

    struct snode *next;
}Symbol;

感谢所有提供帮助的人!

**第一次编辑- phead 是指向列表头部的指针。 plast 是指向列表最后一个节点(Symbol)的指针。 在其他函数中初始化。 plast->next 始终为 null。(这是在函数的开头 - 因为我想确定)。

**第二次编辑- 创建函数 -

void csymbl(Dword addess, char *name, Dword ext, Dword ope ){

tempnode.adess=addess;/*tempnode is a global Symbol,that been used to insert new nodes.*/

strcpy(tempnode.label,name);

tempnode.feature.ext=ext;

tempnode.feature.oper=ope;

tempnode.next=NULL;}

以及将它连接到列表的函数:

void addsymbol(Symbol a){

if(phead==NULL)/*if phead point to NULL - meaning this is the first symbol been entered & up now the linked list was empty. */
{
    phead=&a;
    plast=phead;
}
else if(plast==phead)/*If plast point to phead,than there is only one symbol in the list(up to now).*/
{
    plast=&a;
    phead->next=plast;
    plast->next=NULL;
}
else
{
    plast->next=&a;
    plast=plast->next;
    plast->next=NULL;
}}

最佳答案

您的 addsymbol 函数有一个非常 严重的问题,会导致未定义的行为:

void addsymbol(Symbol a){
    if(phead==NULL)/*if phead point to NULL - meaning this is the first symbol been entered & up now the linked list was empty. */
    {
        phead=&a;
        plast=phead;
    }
    ...
}

在上面的代码中,如果 pheadNULL,则将其指向local 变量 一个

局部变量之所以称为局部变量,是因为它们在定义它们的函数内部是局部的,一旦函数返回,局部变量就不存在了。局部变量 lifetime 仅适用于定义它的范围。参数与其他局部变量没有什么不同。

如果您存储指向此类局部变量的指针,则该指针将变得无效,并且当您使用该指针时,您将有未定义的行为。

关于c - 访问非空结构成员时出现段错误-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36135033/

相关文章:

c - GtkListStore 添加(段错误)

c - 无法在我的程序中找到段错误点

c - 为什么这段代码会触发段错误?

c - 用于解释简单指令集的程序

c - 提供特定值但返回错误指针

c - 尝试访问结构中的字符串会导致段错误

c - Gtk 在按钮单击时显示和隐藏容器

c - 使: create a test binary for each file in test directory

c - 初始化菜单系统的结构数组时出错

c++ - DSO 中的 SIGSEGV,混合 C/C++