Segmentation fault for just declaring vectors?

Jul 7, 2011 at 7:49am
Hi,

In my main function I just tried to declare a vector and I received a segmentation fault in that line. I am so frustrated because I didn't do anything. just declaration. I appreciate your help. Part of the code looks like:

#include<vector>
#define FFTLEN 512
int main(){
int x[FFTlen*FFTlen];
for (int i=0;i<FFTLen:i++){
for(int j=0;j<FFTLen;j++){
if (i==j)
x[i*FFTLen+j]=-1;
else
x[i*FFTLen+j]= 0;
}
}
vector<float> h (3,0.3); //segmentation fault here
}
Best regards,
Jul 7, 2011 at 8:04am
Don't use macros to define constants. The correct version would be: const int FFTLen=512;
Aside from that, there's two possibilities: you exhausted the stack size. Stack is severely limited on some systems and your array already takes 1 MiB. Solution: use a vector.
1
2
vector<int> x(FFTlen*FFTlen);
for (int i=0;i<FFTLen;i++)x[i*FFTLen+i]=-1; //set diagonals, rest is already 0 


Another possibility is that you have undefined behavior in some other part of the application.
Running a memory check tool such as valgrind should help you identify any potential problems.
Jul 7, 2011 at 9:47am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <vector>
#define FFTlen 512

int main()
{
  int x[512*512];
  for (int i=0;i<FFTlen;i++){
     for(int j=0;j<FFTlen;j++){
       if (i==j)
         x[i*FFTlen+j]=-1;
       else
         x[i*FFTlen+j]= 0;
     }
   }
  std::vector<float> h (3,0.3); //segmentation fault here
return 0;

}


This code compiles and runs happily without segfault. A valgrind run reveals zero errors. Whatever the problem is, it's not here (or as Athar said, is something specific to your system such as a stack overflow).
Last edited on Jul 7, 2011 at 9:48am
Jul 7, 2011 at 9:55am
Hi Athar. Thnx for the reply! When I tried to use a vector as you suggested, line 1 in your code gave me the same error- segmentation fault. my system looks like:

cpu: x-86 intel dual core 1.86GHz
memory 2GB
can you brief me on the 'undefined behavior' that you mentioned?

Regards,
Jul 7, 2011 at 10:05am
There's a number of errors that don't prevent compilation, but result in so-called undefined behavior.
The effects of such of errors are highly unpredictable. For example, they can cause the program to crash immediately or generate incorrect results, but they could also cause unrelated parts of the code to fail much later (undefined behavior can also cause your goldfish to spew fire, just so you get the idea).
A common error of that sort is writing beyond array bounds.

Edit: and the maximal stack size doesn't really depend on how much RAM your machine has.
1 MiB is far too large for the stack in any case, even if it works on some systems.
Last edited on Jul 7, 2011 at 10:07am
Jul 7, 2011 at 1:07pm
Thanks! Now it works. I made a terrible assignment mistake.
Topic archived. No new replies allowed.