user15356227
user15356227

Reputation:

C bus error when trying to acces a pointer in a pointer list, which is a struct point to a pointer

I get a bus error whenever I try the following to do the following:

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

// The nodes that hold the data
typedef struct node {
    struct node *next;
    struct node *previous;
} Node;

// The list of the data
typedef struct list {
    Node* head; // start of list of data
    Node* tail; // end of list of data
} List;

// A vertex node, e.g. node 1. The list represents all the nodes (aka vertecies) that this vertex is connected to
typedef struct vertex {
    List *L; // all the connected nodes (called nodes but is actually the numbers this node is connected to)
} Vertex;

// the list of all the vertices, which in themselves contain which nodes they are connected to (using a linked list)
typedef struct list_of_vertices {
    Vertex** Lv;
} l_vertex;

// creats a list with init values of NULL, so we do not access garbage memory later on.
List* createL() {
    List* L = malloc(sizeof(List));
    L->head = NULL;
    L->tail = NULL;

    return L;
}

int main() {
    l_vertex* L = malloc(sizeof(l_vertex));
    L->Lv = malloc(sizeof(Vertex)*5); // 5 vertices in the list of vertex

    for(int i = 0; i < 5; i++) {
        L->Lv[i]->L = createL();
    }

    if(!L->Lv[0]->L->head) { // crash (bus error)
        printf("There was no init\n");
    }

    return 0;
}

I do not get any compiler errors. What I am trying to do is have a list of Vertices, each vertex has a linked list with which vertex they are connected to. This means l_vertex -> list of vertices -> individual vertex -> list of connections -> individual connect.

How do I achieve this and why do I get "Bus error"? I know a bus error is, e.g., when you try to access un-allocated memory.

Upvotes: 0

Views: 160

Answers (1)

dbush
dbush

Reputation: 224437

You've defined the Lv member of l_vertex to be a pointer-to-pointer to Vertex:

typedef struct list_of_vertices {
    Vertex** Lv;
} l_vertex;

This means that Lv can contain an array of pointers to Vertex. But then here:

L->Lv = malloc(sizeof(Vertex)*5); 

You allocate space for 5 instances of Vertex instead of 5 instances of Vertex, so you're not allocating the right amount of space. Then when you do this:

L->Lv[i]->L = createL();

The pointer L->Lv[i] has not been initialized, so attempting to dereference it triggers undefined behavior.

What you actually want in l_vertex is to hold an array of Vertex, so change it to:

typedef struct list_of_vertices {
    Vertex *Lv;
} l_vertex;

This subsequently makes the allocation correct. Then you would access a Vertex like this:

L->Lv[i].L = createL();

Upvotes: 2

Related Questions