Reputation: 1435
I wrote linked list on C.
#define MAX_TOKEN_LENGTH 256
struct node {
char *value;
struct node *next;
};
struct node *new_list() {
struct node *head = (struct node*) malloc(sizeof(struct node));
head->value = (char*) malloc(MAX_TOKEN_LENGTH * sizeof(char));
head->next = NULL;
return head;
}
void add_node(struct node *head, char *value) {
struct node *next;
struct node *curr = head;
struct node *new_node;
while(curr->next != 0) {
curr = curr->next;
}
new_node = (struct node*) malloc(sizeof(struct node));
new_node->value = value;
new_node->next = NULL;
curr->next = new_node;
}
void delete_list(struct node* list) {
struct node *curr = list;
while (curr) {
struct node* next = curr->next;
free(curr->value);
free(curr);
curr = next;
}
}
struct node *list = new_list();
add_node(list, "hello");
delete_list(list);
Compiler: GCC. Line curr->next = new_node;
in add_node
function causes an runtime error. Which leads to this error? How to fix it?
Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000000400864
Aborted (core dumped)
Upvotes: 1
Views: 10520
Reputation: 58848
You can only free
a pointer that was returned by malloc
.
You are doing
free(curr->value);
when curr->value
happens to point to the string literal "hello"
, which was not allocated by malloc
.
You could fix it by either:
malloc
(or another function that uses malloc
, such as strdup
)free
ing the value. (But if you have some values that need to be free
d and some that don't, your program needs to remember which ones to free
)Upvotes: 3