Chad
Chad

Reputation: 185

Segmentation Fault With Pointers In Sorted Lists In C

I have a function here that destroys an iterator acting on a sorted list.

void SortedListDestroyTheIterator (SortedListIteratorPtr iter) 
{
    Node pt = NULL;
    Node prev = NULL;
    SortedListIteratorPtr walk;

    walk = malloc(sizeof(struct SortedListIterator)+1);
    SortedListPtr li = iter->list;

    for(pt = li->start; pt!=NULL; pt = pt->next) //problem line of code
    {
        walk = pt->info;
        //delete
        if(walk==iter){
            if(prev==NULL){
                li->start = li->start->next;
            }
            else
            {
                prev->next = pt->next;
            }
        }
        prev = pt;
    }
    free(iter);
}

I have figured out that a segmentation fault occurs with this assignment statement: pt = li->start. Now this line of code is creating a node that points to the starting node of the list. If I type in li->start it works, but once I add the assignment pt=li->start I get a segmentation fault. I do not understand why or how to fix this.

Upvotes: 0

Views: 41

Answers (2)

rcgldr
rcgldr

Reputation: 28826

Is Node a node or a pointer to node? If Node is a structure, then the code should be:

Node * pt = NULL;
Node * prev = NULL;

Although if this fix works, I don't understand why the compiler didn't produce an error or warning.

The example code doesn't show how Node, SortedListPtr, SortedListIterator, or SortedListIteratorPtr are defined.

I didn't check to see if there are other issues.

Upvotes: 1

t0mm13b
t0mm13b

Reputation: 34592

The line pt = NULL seems the culprit.

Look in the for loop code:

for(pt = li->start; pt!=NULL; pt = pt->next ) //problem line of code

Upvotes: 0

Related Questions