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)
{whe开发者_运维百科reto = 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);
}
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) .....
You don't seem to check whether whereto
is being initialized properly in whereto = linkedAdjacencyList[i];
.
The expression whereto -> adj != NULL
uses whereto
as a pointer and dereferences it with adj
at its offset from the beginning of the structure or class. If that statement is segfaulting, it means whereto
has a bad pointer value. Check what comes out of linkedAdjancencyList[]
and don't use it if NULL.
Put an if check above the while loop and check whether whereto is NULL.
if(whereto!=NULL){ while(whereto->adj != NULL)......... }
精彩评论