当我在以下链表实现的删除函数中执行 free() 时,我遇到了分段错误。请看一下并告诉我哪里出错了。当我用 valgrind 运行这个程序时,没有 seg。故障,运行正常。所以我无法找出问题所在。
typedef struct node {
char name[100];
int id;
struct node* next;
} Node;
void insert(Node** p, char* _name, int _id)
{
Node *temp, *prev;
temp = malloc(sizeof(struct node));
temp->next = NULL;
strcpy(temp->name,_name);
temp->id = _id;
if(*p == NULL) {
*p = temp;
}
else {
for(prev = *p; prev->next!=NULL; prev=prev->next);
prev->next=temp;
}
}
/* Delete entry
@params p first element
_id ID to delete
*/
void delete_by_id(Node** p, int _id) {
Node *temp, *prev;
prev = NULL;
for(temp = *p; temp!= NULL; prev = temp, temp=temp->next) {
if(temp->id == _id) {
printf("Deleting entry with id: %d\n", temp->id);
if(prev == NULL)
*p = temp->next;
else
prev->next= temp->next;
free(temp);
return;
}
}
}
以下是主程序的部分代码:
Node* p;
int main() {
...
...
buf[rval]=0;
char* tokens = strtok(buf, "+");
char* strArray[5]; /* up-to 5 words can be stored */
int n = 0;
while (tokens)
{
strArray[n] = malloc(strlen(tokens) + 1);
strcpy(strArray[n++], tokens);
tokens = strtok(NULL, "+");
}
int type = 0;
if(strcmp(strArray[0], "1") == 0)
type = 1;
else
type = 2;
char* name = "";
if(type == 1) {
name = strArray[1];
insert(&p, name, clients[i]);
display(&p);
} else {
name = strArray[1];
rval = search(&p, name);
if(rval) {
delete_by_id(&p, rval);
display(&p);
}
}
for (i = 0; i < 5; i++)
{
if (strArray[i]) // check for null data
free(strArray[i]);
}
...
...
}
int search(Node** p, char* _name) {
Node *temp;
for (temp = *p; temp!= NULL; temp = temp->next) {
if (strcmp((char *)temp->name, _name)==0) {
printf("Name matched: %s\n", temp->name);
return temp->id;
}
}
return 0;
}
Valgrind 抱怨用于 strArray 而不是链表的 malloc 和 free 。