Search code examples
cstructfwrite

Getting a segmentation fault while trying to write a struct instance to a file


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?


Solution

  • 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.