I have segfault while trying to run such code.
struct list;
struct node;
typedef struct list {
struct node ** links;
int size;
int content;
} list;
typedef struct node {
wchar_t value;
struct list* children;
int exists;
} node;
node* newNode(wchar_t value, int exists) {
node *q = (struct node*)malloc(sizeof(struct node));
q->value = value;
q->children = newList();
q->exists = exists;
return q;
}
list* newList(){
list *result = (list*)malloc(sizeof(list));
result->size = 2;
result->content = 0;
result->links = (struct node**) malloc(result->size * sizeof(struct node*));
return result;
}
void resizeList(list* list_pointer){
if(list_pointer->size <= list_pointer->content){
list_pointer->size *= 2;
list_pointer->links = (struct node**) realloc(list_pointer->links, (list_pointer->size) * sizeof(struct node*));
}
}
void pushList(list* list_pointer, node* node_pointer){
if(node_pointer == NULL)
return;
resizeList(list_pointer);
list_pointer->content++;
int i;
node* temp_pointer;
for(i = 0; i < list_pointer->content; i++){
if(list_pointer->links[i] == NULL){
list_pointer->links[i] = node_pointer;
break;
}
if(list_pointer->links[i]->value > node_pointer->value){
temp_pointer = list_pointer->links[i];
list_pointer->links[i] = node_pointer;
node_pointer = temp_pointer;
}
}
}
Calling.
struct list* l = newList();
struct node* n1 = newNode(L'a', 1);
struct node* n2 = newNode(L'b', 1);
struct node* n3 = newNode(L'c', 1);
struct node* n4 = newNode(L'd', 1);
struct node* n5 = newNode(L'e', 1);
struct node* n6 = newNode(L'f', 1);
struct node* n7 = newNode(L'g', 1);
struct node* n8 = newNode(L'h', 1);
pushList(l, n1);
pushList(l, n2);
pushList(l, n3);
pushList(l, n4);
pushList(l, n5);
pushList(l, n6);
pushList(l, n7);
pushList(l, n8);
After first two pushes it fails.
It's supposed to create list based on values stored in nodes. But... it doesn't. It throws segfault. When I changed allocation of memory from "sizeod(node*)" to "sizeof(node)", it works, but presumably cause of allocation of bigger memory. I want to store POINTERS, not STRUCTS in this array.
I'm figthing that 6 hours with no idea what to do.
list_pointer->links, and after doing that you simply assume all pointers in that array will beNULL. That is a mistake, newly allocated memory is not implicitly zeroed, your code will attept to use those faulty pointers and crash.