额外的变量会导致细分错误

时间:2018-12-11 11:05:34

标签: c segmentation-fault

在下面的代码中,我有两个结构。

第一个是book,它使用page描述书的页数。

第二个是library,它使用指针books来保存所有书籍,并带有参数num_book来指示图书馆的书籍总数。

该程序可以编译并完美运行,并且printf结果正常。

但是当我添加额外的变量(例如int x = 1;)时,如代码所示。我仍然可以编译程序,但是运行可执行文件会导致分段错误。

我不知道为什么会这样,因为一切似乎都已正确初始化。谢谢。

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

typedef struct {
    int page;
} book;

typedef struct {
    int num_book;
    book *books;
} library;


int main() {
    library *my_library;
    int n = 5; // number of books in the library

    // extra variable not used
    // uncomment it gives segmentation fault
    // int x = 1;

    my_library->num_book = n;

    my_library->books = (book *) malloc( (my_library->num_book) * sizeof(book) );

    for(int i = 0; i < my_library->num_book; i++){
        my_library->books[i].page = i+10;
        printf("Book %d\n"
               "Number of pages = %d\n",
               i, my_library->books[i].page);
    }

    return 0;
}

3 个答案:

答案 0 :(得分:2)

在声明my_library后添加此行

my_library = malloc(sizeof(*my_library));

答案 1 :(得分:2)

C中,必须使用malloc手动为结构分配内存。

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

typedef struct {
    int page;
} book;

typedef struct {
    int num_book;
    book *books;
} library;


int main() {
    library *my_library = (library *) malloc(sizeof(library));
    int n = 5; // number of books in the library

    // extra variable not used
    // uncomment it gives segmentation fault
    int x = 1;

    my_library->num_book = n;

    my_library->books = (book *) malloc( (my_library->num_book) * sizeof(book) );

    for(int i = 0; i < my_library->num_book; i++){
        my_library->books[i].page = i+10;
        printf("Book %d\n"
               "Number of pages = %d\n",
               i, my_library->books[i].page);
    }

    return 0;
}

答案 2 :(得分:2)

    library *my_library;
    /* ... */
    my_library->num_book = n;
 // ^^^^^^^^^^ junk here

my_library尚未分配(或初始化)可用值。