我有一段代碼,檢查是否已經定義一個宏,如果它不是,那麼它分配一個新的宏的內存並添加它到當前列表中。如果它已經定義,那麼它只是改變宏體,並保持名稱相同。得到一個Seg錯誤11錯誤,並不知道爲什麼
static struct macro *macro_lookup(char *name){
struct macro * temp = ¯o_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 = ¯o_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功能它得到一個賽格故障。
您應該學習如何使用調試器。它將幫助您找出程序崩潰的確切線條,並讓您檢查變量以查看它們中的任何一個是否是例如'NULL'。 Linux中最常見的調試器可能是[GDB](http://www.gnu.org/software/gdb/)。 – 2012-03-13 06:22:52