Reputation: 1
Recently I've been improving my programming skills by coding different data structures, and this is the very beginning!!!
Now I'm writing the linked list, but something annoyed happen and the trouble has been annoyed me for a long time since I am not quite sure about this error, Segmentation fault(core dumped), but I did know I made something wrong in the operation of memory.
link_list.h:
struct LINK_LIST {
char *string;
struct LINK_LIST *next;
}link_list;
==============================
link_list.c:
#include<stdio.h>
#include<stdlib.h>
int init_link_list(struct LINK_LIST *new_link) {
//char *new_string;
int i;
//new_string = (char *)malloc(sizeof(char) * STRING_SIZE);
new_link = (struct LINK_LIST *)malloc(sizeof(struct LINK_LIST));
if (new_link==NULL) {
fprintf(stderr, "Insufficient memory!!!");
return ERROR;
}
//new_link->string = new_string;
new_link->string = NULL;
//new_link->next = NULL;
return OK;
}
Here I defined the init operation, then the insert operation:
int insert(struct LINK_LIST *link, int pos, char *in) {
int i;
if (get_length(link)>=STRING_SIZE) {
fprintf(stderr, "Link list is full!!!");
return ERROR;
}
else {
if (pos < 0 || pos-1 > get_length(link)) {
fprintf(stderr, "Invalid position");
return ERROR;
}
else {
i = 0;
do {
struct LINK_LIST *new_node;
init_link_list(new_node);
new_node->next = link->next;
link->next = new_node;
new_node->string = in;
i += 1;
} while(i<pos-1);
}
}
return OK;
}
Upvotes: 0
Views: 105
Reputation: 13436
You have a bug there :
struct LINK_LIST *new_node;
init_link_list(new_node);
In init_link_list
, the value of the argument is modified :
new_link = (struct LINK_LIST *)malloc(sizeof(struct LINK_LIST));
but that modification is only local to the function ; once you get back to your calling function, that change is lost :
struct LINK_LIST *new_node;
init_link_list(new_node);
// Oops ! new_node's new value is lost !
You have a memory leak (the malloc
's result is lost) and new_node
is not initialized. When you try to access *new_node
, you access a random position in memory, hence core dumps.
There are a few possible corrections, the easiest is to discard your OK/ERROR return values and return either a non-null pointer if malloc succeeded, or NULL if it failed :
struct LINK_LIST *init_link_list(void) {
struct LINK_LIST *new_link = malloc(sizeof(struct LINK_LIST));
if (new_link==NULL) {
fprintf(stderr, "Insufficient memory!!!");
return NULL;
}
new_link->next = NULL;
return new_link;
}
Then, code in insert becomes :
...
else {
i = 0;
do {
struct LINK_LIST *new_node = init_link_list();
// Note : here, should check whether new_node is NULL and deal with the situation
new_node->next = link->next;
link->next = new_node;
...
Upvotes: 2