[英]Segfault when using fscanf
I am currently trying to read multiple floats from a file. 我目前正在尝试从文件读取多个浮点数。 When I use just one variable it works fine, but there are issues when saving to multiple floats: 当我只使用一个变量时,它可以正常工作,但是保存到多个浮点数时会出现问题:
float r_testdata[3276334];
float i_testdata[3276334];
int e = 1;
FILE *fpI_i = fopen("/home/users/Documents/document.dat","r");
for(int i = 0; i < 3276334;i++) {
e = fscanf(fpI_i,"%f %f",&r_testdata[i],&i_testdata[i]);
if(e != 1) {
fprintf(stderr,"Error reading file\n");
}
}
fclose(fpI_i);
When fscans runs with 2 reads it segfaults. 当fscans以2读取运行时,它会出现段错误。 It seems like a formatting issue with fscanf, but I am failing to see what the issue is. 似乎是fscanf的格式问题,但我无法看到问题所在。 I have looked at posts with similar issues and it has not been fixed. 我看过类似问题的帖子,但尚未修复。
It seems likely you have a stack overflow due to huge arrays. 似乎由于数组大而导致堆栈溢出。 If they are inside a function like: 如果它们在像这样的函数中:
void foo(void)
{
float r_testdata[3276334];
float i_testdata[3276334];
the stack is too small to hold them and that result in memory corruption and a segfault. 堆栈太小而无法容纳它们,从而导致内存损坏和段错误。
You can make them global like: 您可以将它们设置为全局,例如:
float r_testdata[3276334]; // Declared outside the function
float i_testdata[3276334];
void foo(void)
{
or better use dynamic memory allocation using malloc
. 或者最好使用malloc
使用动态内存分配。 Like: 喜欢:
float *r_testdata = malloc(3276334 * sizeof(float));
and when your done with r_testdata
remember to call free(r_testdata);
当您完成r_testdata
的操作后,记得调用free(r_testdata);
As mentioned by @BLUEPIXY: 如@BLUEPIXY所述:
This line is wrong: 这行是错误的:
if(e != 1) {
You are trying to read two values so you must use: 您正在尝试读取两个值,因此必须使用:
if(e != 2) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.