lyoder lyoder - 2 months ago 7
C Question

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. It seems like a formatting issue with fscanf, but I am failing to see what the issue is. I have looked at posts with similar issues and it has not been fixed.

Answer

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. Like:

float *r_testdata = malloc(3276334 * sizeof(float));

and when your done with r_testdata remember to call free(r_testdata);

As mentioned by @BLUEPIXY:

This line is wrong:

if(e != 1) {

You are trying to read two values so you must use:

if(e != 2) {