Program received signal SIGSEGV, segmentation fault, Linked list program

戏子无情 提交于 2019-12-13 09:37:45

问题


#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int value;
    struct node* next;
}Node;

Node* createNode(int data);
Node* insertFront(Node* first, Node* newNode);
void printList(Node* first); 
void deleteList(Node* first);

int main(int argc, const char **argv)
{
    int numItems, ch;
    FILE *fp;

    fp = fopen(argv[1], "r");
    while ((ch = getc(fp)) != EOF)
    {
        if (ch = '\n') numItems++;
    }
    fclose(fp);

    Node *first = NULL;
    Node *newNode;
    Node *Next;

    int i;

    for(i = 1; i <= numItems; i++)
    {
        newNode = createNode(i);
        first = insertFront(first, newNode);
    }

    printList(first);
    deleteList(first);

    return 1;
}

Node* createNode(int data)
{
    Node *newNode;

    newNode = malloc(sizeof(Node));

    newNode -> value = data;

    newNode -> next = NULL;

    return newNode;
}

Node* insertFront(Node* first, Node* newNode)
{
    if (newNode == NULL) {
        /* handle oom */
    }

    newNode->next=NULL;

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

    else {
        Node *temp=first;

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

        temp->next=newNode;

        first = newNode;
    }

    return first;
}

void printList(Node* first)
{
    Node *temp;
    temp=first;

    printf("elements in linked list are\n");
    while(temp!=NULL)
    {
        printf("%d\n",temp->value);
        temp=temp->next;
    }
}

void deleteList(Node* first)
{
    Node  *temp;
    temp=first;
    first=first->next;
    temp->next=NULL;
    free(temp);
}

Tried running with gdb and this is what I got, first real experience trying to make a linked list.

Program received signal SIGSEGV, Segmentation fault. _IO_getc (fp=0x0) at getc.c:40 40 _IO_acquire_lock (fp);

I'm not sure what I'm doing wrong here? Thanks for any tips in advance.


回答1:


You did not initialize numItems to zero. As unitialized it can be any number, including e.g. negative ones. Because of this your list is not created, hence pointer first points to NULL. Then the code segfaults in the function deleteList, when it tries to free memory at location NULL.



来源:https://stackoverflow.com/questions/18688186/program-received-signal-sigsegv-segmentation-fault-linked-list-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!