gpt4 book ai didi

c - 收到 Seg Fault 11 错误,但不知道原因

转载 作者:行者123 更新时间:2023-11-30 15:58:30 25 4
gpt4 key购买 nike

我有一段代码,用于检查宏是否已定义,如果没有,则为新宏分配内存并将其添加到当前列表中。如果它已经定义了,那么它只是更改宏体,并保持名称不变。

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 设置为 null 并测试它,它工作正常,但是当我使用 Macro_lookup 函数时,它会出现段错误。

最佳答案

macro_lookup()中,您检查temp->next不是NULL,但是temp又如何呢?是NULL?另外,temp->macro_nameNULL 又如何呢?或者未初始化?或者 nameNULL 或未初始化?当出现段错误时,调试器会向您显示什么?另外,您没有增加 temp (这很糟糕,因为您的循环永远不会结束)。

关于c - 收到 Seg Fault 11 错误,但不知道原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9678877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com