In the following code, I have two structs.
The first one is book
which describes the number of pages of the book using page
.
The second one is library
which holds all the books using a pointer books
, with the parameter num_book
which tells the total number of books of the library.
The program can be compiled and run perfectly fine, and the printf
result is OK.
But when I added the extra variable (e.g. int x = 1;
) as shown in the code. I can still compile the program, but running the executable gives segmentation fault.
I have no idea why it is the case since everything seems to initialized properly. Thanks.
#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;
}