尝试将结构实例写入文件时遇到分段错误 [英] 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;
}
有人可以帮助我了解seg错误并实现程序的目的吗?
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);
...
或者因为想要那样使用malloc
来分配内存:
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);
...
别忘了在指针无法到达之前调用free
.
Don't forget to call free
before the pointer goes out of reach.
这篇关于尝试将结构实例写入文件时遇到分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文