Schemer
Schemer

Reputation: 1675

C Segmentation Fault

I can't find the seg fault in the following code and I'm hoping someone can point it out for me.

I have a singly linked list of the following structs whose id's are consecutive starting from 0:

typedef struct basic_block_struct
{
    int id;
    bit_vector *dominators;
    struct basic_block_struct *next;
} basic_block;

Later, when the list needs to be searched a lot I try to use an array of pointers to each block in the list to take advantage of indexing. There should be a one to one correspondence between the id's of the blocks and the indices of the array:

basic_block **dom_array = (basic_block **)malloc(num_bb * sizeof(basic_block *));

basic_block *search_bb;
search_bb = head; //The head of the list of blocks

while (search_bb != NULL)
{
    dom_array[search_bb->id] = &*search_bb; //Not sure the &* is needed
    search_bb = search_bb->next;
}

set_bit(dom_array[0]->dominators, 0, TRUE);

It is definitely the last line that is causing the seg fault. The function call is legal -- it just sets the first bit (bit 0) of the bit_vector "dominators" in the first block -- but it appears it is not pointing to a basic_block.

Any advice is appreciated.

Regards.

Upvotes: 1

Views: 191

Answers (2)

Michael Dillon
Michael Dillon

Reputation: 32392

Whenever you get a segmentation fault and can't see the answer in less than a minute, use valgrind. Here is a valgrind tutorial that shows what it can do. Object oriented programmers use unit tests every time they change their code. C programmers should use valgrind the same way.

Upvotes: 1

Schemer
Schemer

Reputation: 1675

Ah, mystery solved. I outsmarted myself. That bit_vector never gets allocated. :-(

Upvotes: 0

Related Questions