daniel
daniel

Reputation: 587

Debugging the following function (Segment fault error)

Is there anything wrong with the following functions?. Somehow, they are creating a segment fault.

struct processNode* create_node()
{
    struct processNode* newNode =  (struct processNode*)malloc(sizeof(struct processNode));
    newNode->next = NULL;
    return newNode;
}

struct processNode* append_node(struct processNode* list,struct processNode* newNode )
{
    struct processNode* tracker= NULL;
    tracker = list;

    if(tracker == NULL)
    {
        tracker = newNode;
    }
    else
    {
        while(tracker->next != NULL)
        {
            tracker =tracker->next;
        }
        tracker->next = newNode;
        tracker = tracker->next;
    }

    tracker->next=NULL;
    tracker = list;
    return tracker;
}

I am creating a shell in C and need to create a link list to parse the command lines from the user. In the second function, I intend to return a new list with the new appended pointer;

Upvotes: 0

Views: 51

Answers (2)

4386427
4386427

Reputation: 44246

I suppose the function shall return a pointer to the head of the list.

Assume the function is called with list being NULL

So this is fine:

    if(tracker == NULL)
    {
      tracker = newNode;
    }

but here

    tracker = list;   <---- Not good....
    return tracker;

You overwrite tracker and return NULL

You could try like:

struct processNode* append_node(struct processNode* list,struct processNode* newNode )
{
    struct processNode* tracker= NULL;
    tracker = list;

    if(tracker == NULL)
    {
        tracker = newNode;
        return tracker;        // Notice
    }

    while(tracker->next != NULL)
    {
        tracker =tracker->next;
    }
    tracker->next = newNode;

    return list; 
}

Upvotes: 1

Shridhar R Kulkarni
Shridhar R Kulkarni

Reputation: 7063

The following cases will give you seg fault here on line tracker->next=NULL;:

  1. tracker != NULL && newNode == NULL
  2. tracker == NULL

        ....
    tracker = tracker->next;
    }
    
    //THE FOLLOWING LINE WILL CAUSE PROBLEM
    tracker->next=NULL; 
    tracker = list;
    return tracker;
     ....
    }
    

You can do like this:

struct processNode* append_node(struct processNode* list,struct processNode* newNode )
{
    struct processNode* tracker= NULL;
    tracker = list;

     if(!newNode){
        //Do nothing 
     }          
    else if(tracker == NULL)
    {
        tracker = newNode;
    }
    else
    {
        while(tracker->next != NULL)
        {
            tracker = tracker->next;
        }
        tracker->next = newNode;
        tracker = tracker->next;
    }

    return tracker;
}

Upvotes: 0

Related Questions