-1

I keep getting this Segmentation Fault: 11 error and I don't know why.

My Code:

typedef struct Node* NodePtr;
struct Node
{
    NodePtr next;
    void *val;
};

struct List
{
    NodePtr head;
};
typedef struct List* ListPtr;

int compare(void *one, void *two)
{
    if(*(int*)one < *(int*)two)
        return -1;
    else if(*(int*)one > *(int*)two)
        return 1;

    return 0;
}

ListPtr create()
{
    ListPtr blah = malloc(sizeof(struct List));
    memset(blah, 0, sizeof(struct List));

    return blah;
}

NodePtr scan(NodePtr head, void *obj)
{
    NodePtr previous, current;

    previous = head;
    current = head->next;      // Segmentation fault here!!

    while(current != NULL && (compare(curry->val, obj) == -1))
    {
        previous = current;
        current = current->next;
    }

    return previous;
}

int insert(ListPtr llist, void *obj)
{
    NodePtr newobj = malloc(sizeof(struct Node));
    NodePtr prevNode, nextNode;

    prevNode = search(llist->head, obj);
    nextNode = prevNode->next;

    if((nextNode == NULL) || (compare(nextNode->val, obj) != 0))
    {
        prevNode->next = newobj;
        newobj->next = nextNode;

        return 1;
    }
    else
    {
        free(newobj);
    }

    return 0;
}

I thought head was not allocated, so I added malloc in create for blah->head, but still no luck.

I think the error is here after some debugging: current = head->next.

Any help would be appreciated! Thank you for your time!

EDIT: How I call insert:

int main(int argc, char *argv[])
{
    ListPtr list = create();

    int x = 2;
    int *p = &x;

    while(*p != 0)
    {
        printf("\nEnter a number: ");
        scanf("%d", p);

        if(*p != 0)
            insert(list, p);
    }

    return 0;
}
neby
  • 103
  • 1
  • 2
  • 9

1 Answers1

1

You don’t appear to check whether the list is empty when you scan it. However, without a Minimum Complete Verifiable Example that tells us how you called the function, it is impossible to tell for sure what you did.

Update

Now that you have, that seems to be it. You create an empty list and search it inside your insert function. The search function dereferences the zeroed-out pointer in head, causing a segfault.

Try the following: first, check that your pointer is valid in each of your functions before you do anything with it. An empty list should fail every search. Second, for maximum portability, you want to set your head pointer to NULL (since a NULL pointer is not necessarily all-bits-zero on all implementations).

Community
  • 1
  • 1
Davislor
  • 14,674
  • 2
  • 34
  • 49