So on a project I’m working on I’m getting the following error:
*** glibc detected *** ./social_network: munmap_chunk(): invalid pointer: 0x09a913b0 ***
A few printf statements revealed the the struct I’m freeing that causes this error has a memory address of….17. So how is this possible? What could have happened to make this appear…?
Here’s some output right before the crash:
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
And here’s the code that outputs the output
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 }
EDIT:
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
I don’t see anything in your code that would suggest that you are freeing a struct at address
17, as you seem to incorrectly believe.Both the crash message and your dump clearly show that you are attempting to free pointer
tempthat points to address162075568(0x09a913b0). That pointer points to invalid memory, which is whyfreecrashes. This is also why you might see17stored inside that memory. That memory is invalid, so there’s nothing surprising in the fact that it stores random garbage.Forget about that
17. It has nothing to do with anything. You problem is162075568(0x09a913b0). This value is invalid and that is the source of the problem.