I am trying to write a struct to a file, but am getting a segmentation fault at run time:
#include<stdio.h>
//just a struct for purposes of demonstration
struct my_struct{
int prop1;
int prop2;
};
//writes dummy struct to filename.dat
void writeStruct(){
FILE *file_pointer;
file_pointer = fopen("filename.dat","w");
//define and assign variables to a quick dummy struct
struct my_struct *this_struct;
this_struct->prop1=0; //seg faults here!
this_struct->prop2=1;
//write struct to file
fwrite(this_struct, sizeof(*this_struct), 1, file_pointer);
fclose(file_pointer);
}
int main(){
writeStruct();
return 0;
}
Can anyone help me understand the seg fault and achieve the purpose of the program?
You've only defined a pointer of the struct, not pointing to any memory. So just don't use a pointer:
...
//define and assign variables to a quick dummy struct
struct my_struct this_struct;
this_struct.prop1=0;
this_struct.prop2=1;
//write struct to file
fwrite(&this_struct, sizeof this_struct, 1, file_pointer);
...
Or since it's wanted that way use malloc
to allocate the memory:
...
//define and assign variables to a quick dummy struct
struct my_struct *this_struct;
this_struct = malloc(sizeof *this_struct);
this_struct->prop1=0;
this_struct->prop2=1;
//write struct to file
fwrite(this_struct, sizeof *this_struct, 1, file_pointer);
...
Don't forget to call free
before the pointer goes out of reach.
You didn't allocate memory for the struct, that's why you got a seg fault.
Also you need check the file_pointer before use it. if the file fail to open, you will also get into trouble.
You declared this_struct as a pointer but didn't initialize it (= new or malloc). The segfault happens because the uninitialized pointer is random.
You should either assign the pointer to a new or malloc object, or declare it as a non pointer and when you write it use &this_struct.