2013-03-14 90 views
0

这里是数据的结构:用C结构的内部结构引起分段错误

struct variabile { 
     char* nome;   
     char* contenuto;   
     struct variabile* next;  
     int tipo;   
    }; 

这里是代码:

struct variabile* pt = malloc (sizeof (struct variabile)); 
      pt->nome = $1; 
      pt->tipo = type; 
      pt->contenuto = $2; 
      pt->next=NULL;  


    if (testaVariabile == NULL) 
      testaVariabile=pt; 
    else { 
      struct variabile* current = testaVariabile; 


     while ((current->next)!=NULL){ 

      if(strcmp(current->nome, pt->nome)==0) 
            fprintf (stderr, "warning: clash di nome di variabili %s \n", current->nome); 
      current=(current->next); 
     } 
     (current->next)=pt; 

     if(strcmp(current->nome, pt->nome)==0) 
       fprintf (stderr, "warning: clash di nome di variabili %s \n", current->nome); 
    } 

这里是可变testaVariabile的初始宣布

 struct variabile* testaVariabile = NULL; 

我得到一个分段错误,当我尝试在最后一行代码更新的当前下一个值。 我也验证过,代码没有输入,而循环。

我对C很新,所以请解释一下答案。

谢谢

编辑

代码的其余部分是一个Flex解​​析器。

编辑

我的一个朋友告诉我用gdb调试。它配备的是错误的

 strcmp(current->nome, pt->nome) 

卡梅斯了我对找错了地方的问题,损失的时间真的很抱歉,但是这是我第一次严重的一次使用C和Flex。

有人知道如何摆脱这个问题?

好的,上次更新。

检查的答案解决了问题。 但是在这种情况下,词法分析器从文件中读取值的方式也存在错误,所以这是一个两部分问题。

+0

你没有关闭一段时间。 – 2013-03-14 02:07:01

+0

对不起,我的错误复制 - 通过代码 – 2013-03-14 02:08:28

+0

你给我们展示的部分看起来不错。发布实际的代码或使用gdb来调试你的代码。 – perreal 2013-03-14 02:12:04

回答

0

试试这个:

struct variabile* pt = malloc (sizeof (struct variabile)); 
pt->nome = malloc(strlen($1) + 1); 
strcpy(pt->nome, $1); 
pt->tipo = type; 
pt->contenuto = $2; // maybe the same for this too? 
pt->next=NULL; 

/* rest of your code ... */ 

只是胡乱猜测,虽然

+0

这当然确实修复了一个错误。 – 2013-03-14 03:05:53