我有以下代码执行插入到我称为symrec(代表符号记录)的结构中。
symrec *createSymStruct(char const * varName, type * type, symrec ** tabella){
symrec * s;
printf("creating new varibale for struct\n");
char * variableName = malloc(strlen(varName)+1);
strcpy(variableName,varName);
s = getsymStruct(variableName, *tabella);
if (s == 0){
printf("putting symbol into table\n");
s = putsymStruct(variableName, NULL, &(*tabella));
}
s->tipo = type;
return s;
}
和被调用的函数
symrec
*putsymStruct(char const * identifier, type * tipo, symrec ** tabella){
printf("\tputting symbol in the table\n");
symrec *ptr = (symrec *) malloc (sizeof (symrec));
ptr->name = (char *) malloc (strlen (identifier) + 1);
strcpy (ptr->name,identifier);
ptr->tipo = (type*)malloc(sizeof(type));
ptr->tipo = tipo;
ptr->next = (symrec*)tabella;
*tabella = ptr;
return ptr;
}
我目前只有一个这种类型的函数调用,我建立了一个函数来打印出符号表的值
void readTable(symrec * tabella){
printf("PRINTING TABLE\n");
if(tabella == NULL){
printf("table is empty\n");
}
symrec *ptr;
for (int i = 0; i < 20; i ++) {
printf("_");
}
printf("\n");
for (ptr = tabella; ptr != (symrec *) 0;
ptr = (symrec *)ptr->next){
printf("|\t%*s\t|\n",20,ptr->name);
}
printf("\n");
}
令人惊讶的是,当桌子被打印时,我找到了一个我没有放的变量,更可能是一个没有清理的记忆空间,或者在声明中我做错了什么......以下是输出..你能帮我找出问题所在吗?任何提示?我没有在分配期间清理内存还是什么?
PRINTING TABLE
____________________
| ciao |
| ?:?0? |
答案 0 :(得分:0)
这听起来不对。
ptr->next = (symrec*)tabella;
也许你的意思是
ptr->next = *tabella;
此外,
ptr->tipo = tipo;
导致内存泄漏。从上一行malloc()
返回的值将丢失。