Why my program throws the error "Segmentation fault"?

The code:

#include <iostream>

#include <algorithm>

#include <valarray>

#include <iterator>

using namespace std;

int main()

{

int i;

valarray<int> va(15),vb;

for(i=0;i<15;i++)

{

va[i]=2*i;

}

cout<<"The elements of Valarray va are:"<<endl;

copy(&va[0],&va[va.size()],ostream_iterator<int> (cout," "));

cout<<endl;

slice vaslice(1,3,4);

vb=va[vaslice];

cout<<"The elements of va's slice(1,3,4) are:"<<endl;

copy(&vb[0],&vb[vb.size()],ostream_iterator<int> (cout," "));

cout<<endl;

return 0;

}


The message from gdb:
(gdb) r
Starting program: /home/[usename]/t
The elements of Valarray va are:
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28

Program received signal SIGSEGV, Segmentation fault.
0x08048ee7 in void std::__valarray_copy<int>(int const*, unsigned int, unsigned int, int*) ()
A segmentation fault occurs when you are trying to use something from memory without declaring it or simply when you are missing a bracket somewhere... To avoid such faults always indent your code properly.
Last edited on
Build the executable with debug symbols included and run it under gdb again. It will tell you exact line that causes the segfault, and you can then check the values of the variables to see which one has a value that causes the problem.
I have had found the problem I missed somedays ago.When I declare the varlable "vb" ,I don't give it a physical space,so
the varlable "vb" points somewhere you don't kown.While you want to assign a value to the "vb",the error occurs.
I have found a "stupid" idea to avoid it to throws the error "Segmentation fault",the 9 line
"valarray<int> va(15),vb;" would be changed to "valarray<int> va(15),vb(3);".

If you have a good idea,tell me!Thank you advance!

Build the executable with debug symbols included and run it under gdb again. It will tell you exact line that causes the segfaul


Except when it won't. It usually doesn't. :(
Last edited on
Except when it won't. It usually doesn't.


Are you using it correctly? I use it regularly and have never had it fail to tell me. I struggle to understand what kind of crazy code or operating system could make it fail to tell you. Are you definitely including the debug symbols? And attaching the debugger to the right process? I genuinely cannot understand how it could fail on a regular basis. Catching segFaults is something gdb does really well.
Topic archived. No new replies allowed.