两位数字指针?这怎么发生的?

时间:2012-11-16 15:12:44

标签: c pointers memory-management free

因此,在我正在处理的项目中,我收到以下错误:

*** 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 }

编辑:

struct friend_node

 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 }; 

struct user_node

 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    

4 个答案:

答案 0 :(得分:7)

当您使用NULL指针时,通常会发生这种情况。你看,当你访问struct的成员时,它的偏移量被添加到指针然后被解引用:

somestruct *p = NULL;
printf("%d", p->member);

如果该成员处于抵消状态,例如0xC,那么您将不会收到“尝试访问0x0内存”这样的错误,而是“尝试以0xC访问内存”。

编辑:正如其他人所说,这可能不是您问题的原因。但这是在“两位数指针”处收到错误的一个常见原因。

答案 1 :(得分:2)

  

可能会出现这种情况

有许多种未定义的行为。所有人都会想到缓冲区溢出,对已解除分配的对象的访问,未初始化的变量。

在追捕这些事情时,valgrind是你最好的朋友。经常使用它。

答案 2 :(得分:2)

我的代码中没有看到任何暗示您在地址17释放结构的内容,因为您似乎错误地相信了。

崩溃消息和转储都清楚地表明您正在尝试释放指向地址temp162075568)的指针0x09a913b0。该指针指向无效内存,这就是free崩溃的原因。这也是您可能会在内存中看到17的原因。该内存无效,因此存储随机垃圾的事实并不令人惊讶。

忘掉17。它与任何事情无关。您的问题是1620755680x09a913b0)。该值无效,这是问题的根源。

答案 3 :(得分:0)

确保在创建/分配struct时初始化指向NULL的所有struct成员。

相关问题