WannaBeCoder
WannaBeCoder

Reputation: 53

Segmentation Fault(Core Dump) Linked List

I'm pretty much at my wits end here. After having this code work (mostly) fine. I compiled it by doing "gcc -o selfRef selfRef.o" as opposed to "gcc -c selfRef.c" Not sure whats the proper way to compile a C file, but I began to get the segmentation fault error, I cant seem to figure out how to fix it.

I inserted print statements in my insert method, so I know that the code isn't even calling it before it breaks. Any idea how to fix this?

Thanks

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdbool.h>    
    struct Node
    {
    int value;
    struct Node *next;
    };    
    struct Node *head;    
    int main( int argc, char* argv[] )
    {
     #define True 1
     #define False 0
     typedef int Boolean;    
     struct Node *head = NULL;   
     int i;    
     printf("Your linked list:\n");    
    //inserts items into the list
     for (i = 1; i < 20; i += 2)
     {
        insert(i,&head);
     }     
     printList(head);
    }
    insert(int x, struct Node **pL)
    {
        printf("Inserts");      
        if(*pL == NULL)
        {
        struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
        (*pL) = temp;
        (*pL) -> value = x;
        (*pL) -> next = NULL;
        }
        else
        {
         insert(x,&((*pL) -> next));
         printf("Inserts");
        }
     }    
    delete(int x, struct Node **pL)
    {
        if(*pL == NULL)
        {
         if(((*pL) -> value) == x)
         {
            (*pL) = (*pL) -> next -> next;
         }
        else
        {
            lookup(x, head -> next);
        }
    }
  }
lookup(int x, struct Node *head)
{
    if(head -> next == NULL)
    {
        return;
    }
    else if(head -> value == x)
    {
        return True;
    }
    lookup(x,(head) -> next);
}   
printList(struct Node *head)
{       
     if(head == NULL)
     {
        printf("The list is empty");
        return;
     }
     printf("Node: %s",head -> value);
     printList(head -> next);       

}

Upvotes: 2

Views: 113

Answers (1)

Christian Davis
Christian Davis

Reputation: 334

Your runtime error is around line 127 in the printList function. The culprit is printf:

printf("Node: %s",head -> value);

You used %s instead of %d. %s is intended for strings. So, printf thinks you have a string and is running wild searching for a null terminator (strings in C are null terminated), but you only gave it an int, so it went off out of the bounds of your memory and you get a segfault.

This change causes the program to finish normally:

printf("Node: %d",head -> value);

This may seem trivial, but a printf memory issue is classic C. Most notorious C exploits are buffer overflows exploiting print functions.

Upvotes: 4

Related Questions