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

纵然是瞬间 提交于 2020-01-06 03:29:45

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/30282076/getting-a-segmentation-fault-while-trying-to-write-a-struct-instance-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!