2013-03-14 98 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