Solving Segmentation Fault: Debugging C++ on Linux

  • Thread starter n1person
  • Start date
  • Tags
    Fault
In summary, the code seems to be working fine on one computer, but when moved to another, causes a segmentation fault.
  • #1
n1person
145
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
  • #2
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];
 
  • #3
You potentially overwrite the stack. You are reading 1000 lines and putting the values in arrays with 10 elements only.
 
  • #4
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:
 
  • #5
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.
 
  • #6
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.
 
  • #7
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.
 
  • #8
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...
 
  • #9
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).
 

1. What is a segmentation fault in C++?

A segmentation fault, also known as a segfault, is a type of error that occurs when a program tries to access a memory address that it does not have permission to access. This can happen due to a variety of reasons, such as trying to access a null pointer or accessing memory that has already been deallocated.

2. How do I debug a segmentation fault in C++ on Linux?

To debug a segmentation fault in C++ on Linux, you can use a debugger like GDB or Valgrind. These tools will help you pinpoint the exact location in your code where the error is occurring, allowing you to identify and fix the issue.

3. What are some common causes of segmentation faults in C++?

Some common causes of segmentation faults in C++ include dereferencing a null pointer, accessing memory that has already been freed, and writing to a read-only memory location. Other causes may include stack overflow, buffer overflows, and invalid memory access.

4. How can I prevent segmentation faults in my C++ code?

To prevent segmentation faults in your C++ code, you should always make sure to properly allocate and deallocate memory, avoid dereferencing null pointers, and carefully manage your program's stack and buffer sizes. It is also important to thoroughly test and debug your code to catch any potential errors before they occur.

5. Can segmentation faults be caused by hardware issues?

Yes, segmentation faults can be caused by hardware issues such as faulty RAM or a damaged hard drive. It is important to rule out any hardware problems before assuming that a segmentation fault is solely due to errors in your code.

Similar threads

  • Programming and Computer Science
Replies
15
Views
2K
  • Programming and Computer Science
4
Replies
119
Views
15K
  • Programming and Computer Science
Replies
32
Views
2K
  • Programming and Computer Science
Replies
2
Views
3K
  • Programming and Computer Science
Replies
4
Views
2K
  • Programming and Computer Science
Replies
6
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
5
Views
2K
Replies
6
Views
1K
  • Programming and Computer Science
Replies
16
Views
11K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
1K
Back
Top