Thread 1 received signal SIGSEGV, Segmentation fault

Viewed 1643

I tried to debug my code using gdb: I am getting error saying

Thread 1 received signal SIGSEGV, Segmentation fault

here is my code:

typedef struct list {
    node *head;
    node *tail;
    int number_of_nodes;
} List;

typedef struct queue {
    List *ptr_list;
} Queue;

void queue_initialize(Queue *queue_list) {
    //TODO
    printf("hello inside queue_initialize\n");  
    list_initialize(queue_list->ptr_list);
    printf("hello after queue_initialize\n");
    return;
}

void list_initialize(List *ptr_list) {
    //TODO
    printf("hello in list_initialize\n");
    ptr_list->head = 0;
    printf("hello\n");
    ptr_list->tail = 0;
    printf("hello\n");
    ptr_list->number_of_nodes = 0;
    printf("hello after list_initialize\n");
}

when I call the function queue_initialize(Queue *queue_list) I get this output

hello before queue_initialize
hello inside queue_initialize
hello in list_initialize

but the expected output is:

hello before queue_initialize
hello inside queue_initialize
hello in list_initialize
hello 
hello
hello after list_initialize

can anyone tell me whats wrong with this code? your effort is really appreciated please help me fast

I am pretty sure that error is here in these lines:

ptr_list->head = 0;
ptr_list->tail = 0;
ptr_list->number_of_nodes = 0;
1 Answers

You must allocate the List structure before you can initialize its members:

#include <stdio.h>
#include <stdlib.h>

typedef struct list {
    node *head;
    node *tail;
    int number_of_nodes;
} List;

typedef struct queue {
    List *ptr_list;
} Queue;

void list_initialize(List *ptr_list) {
    //TODO
    printf("hello in list_initialize\n");
    if (ptr_list) {
        ptr_list->head = 0;
        printf("hello\n");
        ptr_list->tail = 0;
        printf("hello\n");
        ptr_list->number_of_nodes = 0;
    }
    printf("hello after list_initialize\n");
}

void queue_initialize(Queue *queue_list) {
    printf("hello inside queue_initialize\n"); 
    if (queue_list) {
        queue_list->ptr_list = malloc(sizeof(List));
        list_initialize(queue_list->ptr_list);
    }
    printf("hello after queue_initialize\n");
}
Related