1

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;
}
K_inverse
  • 357
  • 3
  • 16

3 Answers3

2

Add this line after declaration of my_library

my_library = malloc(sizeof(*my_library));
awakened
  • 192
  • 9
2

In C, you must allocate memory for your struct manually using 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;
}
pmg
  • 106,608
  • 13
  • 126
  • 198
iRhonin
  • 383
  • 3
  • 14
  • 2
    [Don't cast the result of malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – pmg Dec 11 '18 at 11:16
2

In

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

my_library has not been assigned (or initialized with) a usable value.

pmg
  • 106,608
  • 13
  • 126
  • 198