Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

c - Program received signal SIGSEGV, segmentation fault, Linked list program

#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 = '
') 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
");
    while(temp!=NULL)
    {
        printf("%d
",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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...