2012-03-13 78 views
0

我有一段代码,检查是否已经定义一个宏,如果它不是,那么它分配一个新的宏的内存并添加它到当前列表中。如果它已经定义,那么它只是改变宏体,并保持名称相同。得到一个Seg错误11错误,并不知道为什么

static struct macro *macro_lookup(char *name){ 
    struct macro * temp = &macro_list; 
    while(temp->next != NULL){ 
    if(strcmp(temp->macro_name,name) == 0){ 
     return temp; 
    } 
    } 
    return NULL; 
} 

void macro_set(char *name, char *body){ 
    //Need to check to see if a macro is already set for the name if so just change the body 
    struct macro * p = macro_lookup(name); //Will return NULL if macro is not in the list. This line gives me the error of segmentation fault 11, if I comment it out the program works. 
    //Need to make a new macro and add it to the list 
    if(p == NULL){ 
    //Make a new macro 
    struct macro * new_macro = (struct macro *) Malloc(sizeof(struct macro)); //Malloc is my version of malloc, it works just fine. 
    if(new_macro == NULL){ 
     fprintf(stderr,"Error while allocating space for the new marco.\n"); 
     exit(EXIT_FAILURE); 
    } 
    new_macro->macro_name = name; 
    new_macro->macro_body = body; 
    //Create a pointer to the list and traverse it until the end and put the new macro there 
    struct macro * temp = &macro_list; 
    while(temp->next != NULL){ 
     temp = temp->next; 
    } 
    temp->next = new_macro; 
    } 
    //The macro already exists and p is pointing to it 
    else{ 
    //Just change the body of the macro 
    p->macro_body = body; 
    } 
} 

我不知道为什么上面的错误行给了我一个问题,我可以静态集合P为空,测试它,它工作正常,但是当我使用macro_lookup功能它得到一个赛格故障。

+2

您应该学习如何使用调试器。它将帮助您找出程序崩溃的确切线条,并让您检查变量以查看它们中的任何一个是否是例如'NULL'。 Linux中最常见的调试器可能是[GDB](http://www.gnu.org/software/gdb/)。 – 2012-03-13 06:22:52

回答

0

这是有可能的问题:

new_macro->macro_name = name; 
new_macro->macro_body = body; 

通常应该分配的字符串足够的空间,然后复制它们。除非调用代码执行内存分配并将信息释放到macro_set()函数,否则不能简单地将它们交给那样。

如果您已经显示了宏结构的定义,这将会很有帮助。我假设它大致是:

struct macro 
{ 
    char *macro_name; 
    char *macro_body; 
}; 

不是:

struct macro 
{ 
    char macro_name[MAX_MACRO_NAME_LEN]; 
    char macro_body[MAX_MACRO_BODY_LEN]; 
}; 

如果是后者,你只需要使用strcpy(),但你必须之前检查溢出这样做。

1

macro_lookup()您检查temp->next不是NULL,但tempNULL?另外,如何temp->macro_nameNULL?还是未初始化?或nameNULL还是未初始化?当你遇到seg故障时,调试器显示你什么?此外,你不增加温度(这是不好的,因为你的循环永远不会结束)。

相关问题