Reputation: 1764
I'm curious why the following segfault occurs:
typedef struct Book {
char* title;
unsigned int year;
} Book;
int main(int argc, char * argv[])
{
Book *hammy;
printf("Hammy is located at %p.", hammy);
printf("Hammy has the title: %s.", hammy->title);
}
Hammy is located at 0x55a3629e0340.
Segmentation fault (core dumped)
For example, why doesn't hammy->title
print an empty string or \0
or some gibberish or whatever? When the pointer to the (undefined) Book
is created, what does it point to start?
Upvotes: 0
Views: 62
Reputation: 300
Firstly,
Book *hammy;
This means that you are declaring the pointer variable. As it is not initialized with any address of the book variable, it will be containing the random address. That's why segmentation fault.
Secondly,
Variable of the book is not declared so how we can get content of it, declaring a pointer does not mean that we are declaring an instance of the book. We are just telling the pointer that the address stored in hammy will be pointing to an instance of Book type.
Upvotes: 0
Reputation: 164679
hammy
is declared as type Book *
, a pointer to Book, just an integer. But it is uninitialized. It will contain whatever garbage was on the stack at that moment. In my case it's 0.
You can print hammy
because it's just an integer. When you try to dereference the pointer with hammy->title
the operating system won't let you. Either the memory it points to does not belong to the process, or it's null. You get a segmentation fault.
You need to initialize it with something.
Book *hammy = &(Book){
.title="Nothing in This Book Is True, but It's Exactly How Things Are",
.year=1994
};
Upvotes: 1