所以在我正在处理的项目中,我遇到了以下错误:
*** glibc detected *** ./social_network: munmap_chunk(): invalid pointer: 0x09a913b0 ***
一些 printf 语句揭示了导致此错误的我正在释放的结构的内存地址为....17。那么这怎么可能呢?发生了什么事使这看起来......?
这是崩溃前的一些输出:
temp is: 162075592
temp user is 162075408
After free of temp
inside while loop, first line
before free of temp
temp is: 162075760
temp user is 162075480
After free of temp
inside while loop, first line
before free of temp
temp is: 162075568
temp user is 17
这是输出输出的代码
21 void destroy() {
22
23 struct user_node *node;
24
25 struct friend_node *temp;
26 struct friend_node *next_temp;
27
28 //iterate over the list of users
29 while (*head != NULL) {
30 printf("before a_friend\n");
31 temp = (*head)->a_friend;
32
33 //Iterate over friends of users, free friend nodes
34 while (temp != NULL) {
35 printf("inside while loop, first line\n");
36 next_temp = temp->next_friend;
37 printf("before free of temp\n");
38 printf("temp is: %d\n", (int) temp);
39 printf("temp user is %d\n", (int)temp->user);
40 free(temp); <==================================SEGFAULT IS HERE!!!!!!!!!!!!!
41 printf("After free of temp\n");
42 temp = next_temp;
43 next_temp = NULL;
44 }
45
46 node = (*head)->next_user;
47 printf("before free of: %s\n", (*head)->name);
48 free(*head);
49 printf("after free of that person...\n");
50 *head = node;
51 printf("*head = node afterwards\n");
52 node = NULL;
53 }
54 printf("before final free...\n");
55 free(head);
56 }
编辑:
构造 friend 节点
23 //node used to store a pointer to a user_node and next friend
24 struct friend_node {
25 struct friend_node *next_friend;
26 struct user_node *user;
27 };
结构用户节点
12 //Struct definitions
13 //node used to store information about a user
14 struct user_node {
15 char name[21];
16 int age;
17 int gender;
18 char location[21];
19 struct friend_node *a_friend;
20 struct user_node *next_user;
21 };
22
最佳答案
这通常发生在您使用 NULL 指针时。你看,当你访问一个结构的成员时,它的偏移量被添加到指针然后被取消引用:
somestruct *p = NULL;
printf("%d", p->member);
如果成员处于偏移状态,例如0xC,那么你将不会收到类似“试图访问 0x0 处的内存”的错误,而是“尝试访问 0xC 处的内存”。
编辑:正如其他人所建议的,这可能不是您遇到问题的原因。但这是在“两位数指针”处收到错误的常见原因。
关于c - 两位数指针?这怎么发生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13419318/