Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault in NULL check?

I am getting a segmentation fault while trying to check if some elements are NULL or not. Can anyone help?

    void addEdge(int i, int j) 
{
        if (i >= 0 && j > 0) 
    {
        Node* whereto;
        whereto = linkedAdjacencyList[i];
        if(whereto != NULL)
        {
            while(whereto->adj != NULL)
            {whereto = whereto->adj;}
            whereto->adj = linkedAdjacencyList[j];
        }
        else{linkedAdjacencyList[i]->adj = linkedAdjacencyList[j];}
        whereto = linkedAdjacencyList[j];
        if(whereto != NULL)
        {
            while(whereto->adj != NULL)
            {whereto = whereto->adj;}
            whereto->adj = linkedAdjacencyList[i];
        }
        else{linkedAdjacencyList[j]->adj = linkedAdjacencyList[i];}
            }
    }

help!

EDIT: this is the new code, as per your suggestions, but now there is a segmentation fault immediately when the method is called? i'll post the calling...

int edges;
in >> edges;
g.edges = edges;
for(int i = 0; i < edges; i++)
{
    int first;
    int second;
    in >> first >> second;
    g.addEdge(first, second);
}
like image 531
jlehenbauer Avatar asked Mar 07 '26 05:03

jlehenbauer


1 Answers

I suggest that linkedAdjacencyList[i] returns NULL, so you are trying to dereference NULL. Just add extra check for NULL :

Node* whereto = NULL;
whereto = linkedAdjacencyList[i];
if (NULL != whereto){
while(whereto->adj != NULL) .....
like image 118
a1ex07 Avatar answered Mar 09 '26 06:03

a1ex07