Amit
Amit

Reputation: 3990

Segmentation fault in saving file pointer in a struct

I have a file pointer current_file of type FILE *current_file;. When I run this code

current_file = fopen ("file.text", "r");
struct buffer *buf;
buf->file = current_file;

I keep ending with a Segmentation fault (core dumped). Here buffer is a struct like so:

struct buffer {
    FILE *file;
    int size;
};

I am completely stuck wit what's making this die. Thanks for taking time to read this!

Upvotes: 2

Views: 135

Answers (2)

galfisher
galfisher

Reputation: 1122

You haven't initialized buf before using the deference operator in buf->file = current_file;

Upvotes: 3

Florian Heer
Florian Heer

Reputation: 714

You only declare buf to be a pointer of the type buffer, but there is no memory allocated for the struct. Therefore you have an uninitialized pointer.

Upvotes: 5

Related Questions