Getting a segmentation fault while trying to write

2019-07-29 05:08发布

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?

标签: c struct fwrite
3条回答
做自己的国王
2楼-- · 2019-07-29 05:41

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.

查看更多
闹够了就滚
3楼-- · 2019-07-29 05:50

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.

查看更多
Emotional °昔
4楼-- · 2019-07-29 06:03

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.

查看更多
登录 后发表回答