简体   繁体   English

在结构内部使用C Struct会导致分段错误错误

[英]Using C Struct inside struct causes segmentation fault error

Here is the structure of the data: 这是数据的结构:

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

And here is the code: 这是代码:

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

Here is the initial declaration of the variable testaVariabile . 这是变量testaVariabile的初始声明。

       struct variabile* testaVariabile = NULL;

I get a segmentation fault error when I try to update the next value of current in the last line of code. 当我尝试更新代码的最后一行中的下一个 当前值时,出现分段错误错误。 I have also verified that the code didn't enter the while cycle. 我还验证了代码没有进入while周期。

I'm pretty new to C, so please explain the answer. 我对C很陌生,所以请解释答案。

Thank you 谢谢

EDIT 编辑

The rest of the code is a Flex parser. 其余代码是Flex解​​析器。

EDIT 编辑

A friend of mine tell me to debug using gdb. 我的一个朋友告诉我使用gdb进行调试。 It comes out that the error cames out from 结果是错误来自

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

I'm really sorry for the time lost looking for the problem in the wrong place, but this is my first serious time with C and Flex. 我为在错误的位置上找不到问题所付出的时间感到非常抱歉,但这是我第一次使用C和Flex。

Somebody knows how to get rid of this problem? 有人知道如何摆脱这个问题吗?

Ok, last update. 好的,最后更新。

The checked answer solved the problem. 选中的答案解决了问题。 But in this case there was also an error in the way that the lexer read the value from the file, so it was a two-part problem. 但是在这种情况下,词法分析器从文件中读取值的方式也存在错误,因此这是一个两部分的问题。

Try this: 尝试这个:

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 ... */

just a wild guess though 虽然只是一个疯狂的猜测

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

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