Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Having Seg faults, ideas? struct node { int data; struct node *next; }; struct n

ID: 3786817 • Letter: H

Question

Having Seg faults, ideas?

struct node
{
    int data;
    struct node *next;
};

struct node *init()
{
    struct node *new;
    new = malloc(sizeof(struct node));
    new->data=0;
    new->next=NULL;
    return(new);
}

int add(struct node *list, int number)
{
    struct node *thisNode;
    struct node *nextNode;
    struct node *newNode = init(); // returns next free array position
   
    if ((duplicate(list,number)) == 1)
    {
        return(0);
    }
   
   
    newNode->data = number;
    thisNode = nextNode;
    nextNode = nextNode->next;

    while (nextNode != NULL)
    {
       
        if(newNode->data < nextNode->data)
        {
            thisNode->next = newNode;
            newNode->next = nextNode;
            break;
        }
   
    thisNode = nextNode;
    nextNode = nextNode->next;

    }

    if(nextNode == NULL)
    {
        thisNode->next = newNode;
        newNode->next = nextNode;
    }
return (1);

}

int duplicate(struct node *list, int number)
{
    struct node *thisNode;
    struct node *nextNode;
   
    do
    {
        thisNode = nextNode;
        nextNode = nextNode->next; // 4, 3, 2, 6, -1
        if (nextNode == NULL && thisNode->data == number)
        {
            if (thisNode == 0)
            {
                return (0);
            }
           
            return (1);
        }
        if (nextNode == NULL && thisNode->data != number)
        {
            return (0);
        }

    } while(nextNode->data != number);
   
    return (1);
}

Explanation / Answer

There are lot of problem in the program. First things is pointers which are not initialized or NULL are being used which causes segmantation fault.

In function add

thisNode(pointer to struct node) and nextNode are not initialized and using them in expression or assigning them like this

thisNode = nextNode;
nextNode = nextNode->next;

Gives segmentation falut.

Second thing is logic of the program is wrong. add function takes argument list ie pointer to struct node and it's never been used in the program,just passing the list variable to duplicate function without checking weather list is NULL or not .. pointer list should to be updated or used in the program otherwise why it's been passed ,logic is not correct. If you want I can modify program to work according to the specification .. Post with full program requirement.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote