C/C++ Solving Segmentation Fault: Debugging C++ on Linux

  • Thread starter Thread starter n1person
  • Start date Start date
  • Tags Tags
    Fault
Click For Summary
The discussion revolves around a code issue where a program written on a Mac compiles but encounters a segmentation fault when run on a Linux machine. The code attempts to read from a file and store values in arrays, but it has several potential problems. Key points include the declaration of arrays with variable sizes, which is not allowed in C++ and can lead to stack overflow. The code also lacks checks for successful file opening and reading, which can result in undefined behavior if the file is not found or if fewer values are read than expected. Suggestions were made to print the count variable to check for array bounds and to implement error handling for file operations. The original poster later confirmed they resolved the issue. Additionally, a second question was raised about reading multiple files with a naming pattern, where suggestions included using `sprintf` or `snprintf` to construct filenames safely before opening them.
n1person
Messages
144
Reaction score
0
Oh noes! I wrote a code on my mac, it works fine, and then I move it onto my linux machine, it compiles fine (using g++ command), but then when i run it i get a "segmentation error." I've look around a bit online and I couldn't find anything which seems to fit this particular error. I can compile all my other programs fine.

(It is part of a larger program but I was able to isolate this code as problematic)
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main(void)
{
int e;
e=1000; //number of elements in table
int k2;
k2=10;
float array[k2];
float error[k2];
float distance[k2];
float index[k2];
float narray[k2];
float nerror[k2];
float ndistance[k2];


FILE * inFileOne;



float f, p, q; // field1, field2, field3, field4, field5, field6;

inFileOne = fopen ("1.txt","r"); //file hard coded here
int i1;
float x1,x2,x3;
float x11[k2];
float x22[k2];
float x33[k2];
int count;
count=0;
for (i1=0; i1 <e+1; i1++) // test all lines
{
fscanf (inFileOne, "%f%f%f%f%f%f",&x1,&x2,&x3,&f,&p,&q);
if(p < 40)
{
x11[count] = x1;
x22[count] = x2;
x33[count]= x3;
index[count] = f; //Set variables for use to inputs
array[count] = p;
error[count] = q;
count=count+1;
}
else{}
}

}

Thanks for your Help!
 
Technology news on Phys.org
I don't think you can do this:
Code:
int k2;
k2 = 10;
float array[k2];

I tried this using MS Visual Studio 2005 and got 3 compiler errors. The problem is that you are trying to declare an array with a variable number of elements. The number of elements in an array has to be a constant that is known at compile time.

I was able to eliminate the compiler errors by making this change:
Code:
const int k2;
k2 = 10;
float array[k2];
 
You potentially overwrite the stack. You are reading 1000 lines and putting the values in arrays with 10 elements only.
 
Mark44 said:
The problem is that you are trying to declare an array with a variable number of elements. The number of elements in an array has to be a constant that is known at compile time.
Actually, this is perfectly valid standard C code. It hasn't made it into the C++ standard though.


The source of the segmentation fault seems rather clear, though. One of the most common sources is trying to access outside of the bounds of an array. Lo and behold...



Other problems include the fact that the code never checks to make sure that the file opened correctly, or that fscanf actually read the number of values he asked for. :frown:
 
Thanks for the Input, sadly I am away from my linux machine but i made the changes on my mac and will try out the code tomorrow or the next day. I am somewhat doubtful that it is an array overflow problem (the sample file is only 5 lines), but I will try it out.
 
n1person said:
Thanks for the Input, sadly I am away from my linux machine but i made the changes on my mac and will try out the code tomorrow or the next day. I am somewhat doubtful that it is an array overflow problem (the sample file is only 5 lines), but I will try it out.
There's a good way to check if it's an array overflow problem -- try printing count just before you use it as an array index. :smile: In this case, it should be nearly 100% conclusive.


My suspicion that a deeper cause is that fopen failed to open the file -- maybe because it's in the wrong directory or doesn't exist in your linux machine -- but since you never checked, you blissfully tried to read from the file. Since there was nothing to read, fscanf assigned no values and reported such, but you didn't check that either. So your loop just kept going over and over, because the values of x1, x2, and all of those other variables never changed from whatever values they happened to start with.


One other semantic error I missed is that you never seem to actually check if you've read the entire file -- you just blissfully keep trying to read it.


You should always strive to be rather pedantic about file I/O. Sure, it takes a lot of time to put in all the necessary checks, but it takes even more time to debug the problems that arise when things go wrong. :frown: Or, at least, adding in these checks should be one of the first things you do when your code starts acting strangely.
 
n1person said:
Thanks for the Input, sadly I am away from my linux machine but i made the changes on my mac and will try out the code tomorrow or the next day. I am somewhat doubtful that it is an array overflow problem (the sample file is only 5 lines), but I will try it out.

It still can be an array overflow. You do 1000 reads from the input file. As you do not check if fscanf() is successful the stack overflow largely depends on the implementation of fscanf().
It is not specified what is returned in the pointer locations (in this case 'p' is the problem), when EOF is reached.
 
Thanks all! I got it to work! yay!

Second Question:

lets say I have a folder filled with files which have "a.txt" where a is an integer ranging from 1 to 1000 and i want to read all of those files... I have tried using a string but fopen won't take any more commands :( i cannot do fopen("%s", name, "r") :(
any ideas or links to resources, my cursory inspection of the internet leads to nothing overly promising...
 
printf the filename into a string first

eg

char filename[256]
sprintf(filename,"%u.txt",number);
fopen(filename...
 
  • #10
NobodySpecial said:
printf the filename into a string first

eg

char filename[256]
sprintf(filename,"%u.txt",number);
fopen(filename...

Note, although NobodySpecial's code is 100% safe, you should really get in the habit of using snprintf:

char filename[256];
snprintf(filename, 256, "%u.txt", number):
fopen(filename...

This will ensure that snprintf never accidentally writes more bytes into filename than it can safely old (though again this will not occur in nobodyspecial's code, because %u cannot possibly be longer than 10 bytes or so).
 

Similar threads

  • · Replies 15 ·
Replies
15
Views
3K
  • · Replies 119 ·
4
Replies
119
Views
16K
  • · Replies 32 ·
2
Replies
32
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 6 ·
Replies
6
Views
4K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 16 ·
Replies
16
Views
12K
  • · Replies 23 ·
Replies
23
Views
6K
  • · Replies 6 ·
Replies
6
Views
5K
  • · Replies 6 ·
Replies
6
Views
5K