Skip to content
Advertisement

Scanning numbers from a file in C

I tried to scan some coordinates [X, Y, Z] from a file, but always returned as segmentation fault. So, I’ve some questions to make:

  1. I don’t know how many points are in the file, but if I leave the struct arrays empty, there will be an error. There is a way to do this without defining a max number?

  2. Are my use of pointers ok? I’m not very talented with them.

I think that what is causing the segmentation fault is the fscanf, but I can’t fix it

JavaScript

The beginning of the file is like this:

JavaScript

Advertisement

Answer

You have a very large array declared as a local variable:

JavaScript

There are 20000 element in the array, and each array element is (assuming int and float each take up 4 bytes) 4 + 4 * 20000 + 4 * 20000 + 4 * 20000 = 240004 bytes for a total size of 4,800,080,000 ( 4.8 GB ). Even as a global variable, that’s huge. As a local, which on most implementations lives on the stack, this easily exceeds stack size which results in the core dump.

You don’t need an array of these structures, only a single one. Then you use it like this:

JavaScript

Also, don’t use feof

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement