-2
#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);
}

尝试使用 gdb 运行,这就是我得到的,第一次尝试制作链表的真实体验。

程序收到信号 SIGSEGV,分段错误。_IO_getc (fp=0x0) at getc.c:40 40 _IO_acquire_lock (fp);

我不确定我在这里做错了什么?感谢您提前提供任何提示。

4

1 回答 1

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.

于 2013-09-08T20:41:21.290 回答