段错误 11

Segmentation Fault 11

编写此库程序时,当我通过终端 运行 时收到分段错误 11。起初在调试时它似乎位于结构的某个地方,但后来它给了我声明 FILE 指针的问题。有人可以解释一下这个问题吗?

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

#define MAX_LENGTH 40
#define MAX_BOOKS 1000
struct book
{
    char title[MAX_LENGTH];
    char author[MAX_LENGTH];
    char subject[MAX_LENGTH];
}*Book;

    struct library
{
    struct book collection[MAX_BOOKS];
    int num_books;
}*lib;

int main()
{
    struct library *lib;
    char title[MAX_LENGTH], author[MAX_LENGTH], subject[MAX_LENGTH];
    Book = NULL;
    lib->num_books = 0;

    int events = 0, selection = 0;
    FILE *ifp;
    ifp = fopen("library.txt", "r");
    if (ifp == NULL)
    {
        printf("\nFile not found\n");
        exit(0);
    }
    fscanf(ifp, "%d", &events);

    for (int i=0;i<events; i++)
    {
        Book = NULL;
        fscanf(ifp, "%d", &selection);

        switch (selection)
        {
            case 1:
                fgets(title, MAX_LENGTH, ifp);
                fgets(author, MAX_LENGTH, ifp);
                fgets(subject, MAX_LENGTH, ifp);
                strcpy(Book->title, title);
                strcpy(Book->author, author);
                strcpy(Book->subject, subject);
                lib->num_books += 1;
                //addBook(lib);
                break;
            case 2:
                lib->num_books -= 1;
                //deleteBook();
                break;

            case 3:
                //search;
                break;

            case 4:

                break;

            case 5:
                break;

            default:
                printf("Invalid command\n");
                break;
        }
    }

    fclose(ifp);
    return 0;
}

1)错误在下面一行 库->num_books = 0;

指针变量 lib 在没有初始化的情况下被引用。

2) 还有一个错误是,您正在打开文件进行读取操作 "r",但试图使用该文件进行写入操作。

  lib->num_books = 0;

这是在制造问题。您还没有初始化 lib.

为其分配内存-

lib=malloc(sizeof(struct library));

编辑

另外不要忘记free分配的内存。