【发布时间】:2011-04-23 04:49:16
【问题描述】:
看这段代码太久了,我越来越沮丧,任何自己弄清楚它的机会都已经失去了:(任何人都可以告诉我我在哪里愚蠢?我只是不明白我在哪里双重释放或者可能分配不正确(我必须这样做但是是的)。我不断收到 * glibc detected * free(): invalid next size
我实际上是在释放比我需要的更多的东西,还是我只是没有分配我需要分配的东西。 --sorry for bad indentation 无法让这个编辑器正确缩进
我有结构:
typedef int boolean;
typedef char * String;
typedef struct {
char name[30];
long ID;
char address[40];
char city[20];
int age;
}Employee;
typedef struct node {
Employee *anEmployee;
struct node *next;
}NODE;
typedef struct {
NODE *head, *tail;
}SLL;
插入函数--SLL(单链表)
void insert(SLL *list, Employee e){
printf("insert");
NODE *temp, *current;
temp = (NODE *)malloc(sizeof(NODE));
assert(temp != NULL);
temp -> anEmployee = (Employee *)malloc(sizeof(Employee *));
assert(temp -> anEmployee != NULL);
strcpy(temp -> anEmployee -> name, e.name);
temp -> anEmployee -> ID = e.ID;
strcpy(temp -> anEmployee -> address, e.address);
strcpy(temp -> anEmployee -> city, e.city);
temp -> anEmployee -> age = e.age;
if (list -> head == NULL) { /* list is empty */
list -> head = list -> tail = temp;
return;
}
else { // list is not empty
list -> tail -> next = temp;
list -> tail = temp;
}
}
在删除函数中删除和释放内存
boolean delete(SLL *list, String str){
printf("delete");
NODE *temp, *temp2;
if (list -> head == NULL) return FALSE; // list is empty
temp = list -> head;
while ((temp != NULL) && (strcmp(temp -> anEmployee -> name , str) != 0))
temp = temp -> next;
if (temp == NULL) return FALSE; // str is not found in the list
// now temp points to the NODE with str in it. Let us delete it
// from the list
if ( list -> head == temp) { // temp points to the first NODE
if (temp -> next == NULL) { // temp points to the only NODE
list -> head = list -> tail = NULL;
free(temp -> anEmployee);
free(temp);
return TRUE;
}
// temp points to the first NODE but it is not the only NODE
list -> head = temp -> next;
free(temp -> anEmployee);
free(temp);
return TRUE;
}
if (temp -> next == NULL) { // temp points to the last NODE
temp = list -> head;
temp2 = list -> head -> next;
while(temp2 - > next != NULL){
temp = temp->next;
temp2 = temp2 ->next;
}
list -> tail = temp ;
list -> tail -> next = NULL;
free(temp2 -> anEmployee);
free(temp2);
return TRUE;
}
// temp points to some NODE in the middle of the list
temp2 = temp -> next;
while(temp2 - > next != NULL){
temp ->anEmployee = temp2 - > anEmployee //
temp = temp->next;
temp2 = temp2 ->next;
}
temp ->anEmployee = temp2 - > anEmployee
list -> tail = temp ;
list -> tail -> next = NULL;
free(temp2 -> anEmployee);
free(temp2);
return TRUE;
}
【问题讨论】:
-
对于缩进:用四个空格搜索并替换制表符。