Segmentation fault in c++ program using vector - c++

I received a segfault when running my code. The code contains a for loop and segmentation fault doesn't appear when I run the program for smaller iterations. It appears when I run the code for the larger loop.
I used a debugger to check where doe the problem occurs:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004062d0 in std::vector<int, std::allocator<int> >::push_back (
this=0x64dc08, __x=#0x7fffffffd180: 32)
at /usr/include/c++/5/bits/stl_vector.h:915
915 if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)
What does it mean? Does anyone know? The code error is related to this part of the code:
int box_new = getBoxID(x[i],y[i],R0,nbox);
if(bx[i] != box_new)
{
vector<int>::iterator position = std::find(box_particles[bx[i]].begin(), box_particles[bx[i]].end(), i);
if (position != box_particles[bx[i]].end()) // .end() means the element was not found
box_particles[bx[i]].erase(position);
bx[i] = box_new;
box_particles[box_new].push_back(i);
}

Because value of box_new is out of bound, that is, it may be larger than or equals to the size of box_particles or less than 0. Then corruption occur and
segfault.
Please make sure box_new is in the range[0, box_particles.size()). Note that this range may change at each iteration.

Related

Segmentation fault occurs way after index leaves array boundary in C++ [duplicate]

This question already has an answer here:
will Index Out Of Array Bounds throw exception or error before core in C++?
(1 answer)
Closed 5 years ago.
I have this code:
#include <cstdio>
int foo[100];
int main()
{
for(int i=0;i<10000;i++)
foo[i]=10000;
}
Debugging with GDB gives a surprising result:
[New Thread 23684.0x59b4]
[New Thread 23684.0x5c0c]
[New Thread 23684.0x541c]
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401564 in main () at C:\Users\DARREN\Documents\Visual Studio
2017\Projects\Untitled1.cpp:9
warning: Source file is more recent than executable.
9 }
(gdb) print i
$1 = 4080
(gdb)
Now, I know the statement foo[i]=10000 caused the error, but I declared foo to be only of size 100. Why would the value of i be so big before the error occurs?
Any explanation is appreciated.
After you made an update to your question you posted this:
int foo[100];
int main()
{
for(int i=0;i<10000;i++)
foo[i]=10000;
}
And you are asking about segmentation fault.
Here you have an array with a size of 100 and you have a loop that ranges [0,9999] and within the for loop you are indexing the array with the for loops incremental variable i. When you step through the for loop for each iteration of i and you get to:
foo[i] = 10000;
when i <= 99 everything is okay.
What do you suppose happens when i >= 100?
When you use raw arrays there is no bounds checking; and this is something that you and the user will have to be responsible for. If you want automatic bounds checking done for you to prevent this out of bounds memory segmentation fault you should use any of the standard containers such as std::vector<T>, std::list<T>, std::set<T> etc. depending on your needs. If you need to use array index notation then std::vector<T> is the way to go. Or any other vector from any other library such as boost.
EDIT
For you to fix this problem you would have to either increase the size of the array from 100 to 10,000 or you would have to decrease your loop's condition from i<10000 to i<100 to accommodate for proper array indexing. Do not forget that C++ arrays have their starting index at 0 so you would have a basic array and loop as such:
int var[10]; // Uninitialized
for ( int i = 0; i < 10; ++i ) {
var[i] = 0; // Initialize all array indexes to 0
}
Notice that the condition in the for loop is i < 10 which is less than the actual size of the array when it is declared and not i <= 10 less than or equal to for this would also generate a segmentation fault or out of bounds error.

A segmentation fault

I have try the following code to judge prime:
const int N = 200000;
long prime[N] = {0};
long num_prime = 0;
int is_not_prime[N]={1,1};
void Prime_sort(void)
{
for( long i = 2 ; i<N ; i++ )
{
if( !is_not_prime[i] )
{
prime[num_prime++] = i;
}
for( long j = 0; j<num_prime && i*prime[i]<N ; j++ )
{
is_not_prime[i*prime[j]] = 1;
}
}
}
But when I run it, it cause a segmentation fault! That fault I have never meet.And I searched Google,and it explain segmentation fault as follow:
A segmentation fault (often shortened to segfault) is a particular
error condition that can occur during the operation of computer
software. In short, a segmentation fault occurs when a program
attempts to access a memory location that it is not allowed to access,
or attempts to access a memory location in a way that is not allowed
But I don't know where cause this fault in my code.Please help me.
Your array is_not_prime has length N. For example, at the final lap of the outer for loop, i will have the value N-1. When i is that big, is_not_prime[i*prime[j]] will cause you to write far out of bounds of the array.
I'm not quite sure what j<num_prime && i*prime[i]<N is supposed to do, but it is likely part of the bug. Single step through the program with your debugger and see at what values the variables have when the program crashes.
Just re-write your program in a less complex manner and all bugs will go away.
Compare your loop bound checking to your indexing - they aren't the same. (I believe you meant to write i*prime[j]<N in your for loop.)
Your program crashes because an index goes out of bounds. And the index goes out of bounds because your algorithm is not valid.
As it still crashes if you set N at a much smaller value
const int N = 3;
it shouln't be too difficult to see what goes wrong by running your program with pencil and paper...

Segmentation fault disappears when debugging with GDB

I am having a segmentation fault while running this code: http://ideone.com/yU80Bd
The problem is when I run it in GDB, the code runs fine and excellent. Why is this running in gdb with no segfault but running every other place with a segmentation fault?
Here is the problem I am trying to solve: http://www.codechef.com/DEC13/problems/CHODE
The problem is that your input includes characters that are not in the range [a-Z]. For example: ! That causes the vector to be accesed at invalid indexes.
You can check these things running your program with valgrind.
valgrind ./ideone < stdin
...
==2830== Invalid read of size 4
==2830== at 0x40111A: main (ideone.cpp:53)
...
==2830== Invalid write of size 4
==2830== at 0x401120: main (ideone.cpp:53)
The problem is in these lines:
for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
++(cipherF[c-97].frequency);
}
c - 97 may be lower than 0.
You can check, for example:
for(int i=0;i<cipherText.size();++i)
{
char c = tolower(cipherText[i]);
if (c < 'a' || c > 'z') continue;
++(cipherF[c-97].frequency);
}

Mysterious segmentation fault in C++?

I have been searching all over and cannot find anything like this. Now, I won't bore you with my whole program. It's incredibly long. But, here's your basic overview:
int main()
{
int i=0;
int h=5;
cout << "h(IS) = " << h << endl;
cout << "testing comment.";
while(i < 10)
{
cout << "I'm in the loop!";
i++;
}
return 0;
}
Looks great, right? Okay, so here's the problem. I run it, and I get a segmentation fault. The weirdest part is where I'm getting it. That testing comment doesn't even print. Oh, and if I comment out all the lines before the loop, I still get the fault.
So, here's my output, so you understand:
h(IS) = 5
Segmentation fault
I am completely, and utterly, perplexed. In my program, h calls a function - but commenting out both the line that prints h and the function call have no effect, in fact, all it does is give the segmentation fault where the line ABOVE the printing h line used to be.
What is causing this fault? Anything I can do to test where it's coming from?
Keep your answers simple please, I'm only a beginner compared to most people here :)
Note: I can provide my full code upon request, but it's 600 lines long.
EDIT: I have pasted the real code here: http://pastebin.com/FGNbQ2Ka
Forgive the weird comments all over the place - and the arrays. It's a school assignment and we have to use them, not pointers. The goal is to print out solutions to the 15-Puzzle. And it's 1 AM, so I'm not going to fix my annoyed comments throughout the thing.
I most recently got irritated and commented out the whole first printing just because I thought it was something in there...but no...it's not. I still get the fault. Just with nothing printed.
For those interested, my input information is 0 6 2 4 1 10 3 7 5 9 14 8 13 15 11 12
THANK YOU SO MUCH, EVERYONE WHO'S HELPING! :)
You slip over array boundaries, causing the corruption:
for (i=0; i<=4; i++)
{
for (j=0; j<=4; j++)
{
if (cur[i][j] == 0)
{
row = i;
col = j;
}
}
}
Your i and j indices must not reach 4.
valgrind is a great tool for debugging memory access problems. It's very easy to use on Linux. Just install G++ and valgrind, and then run (without the $ signs):
$ g++ -g -o prog prog.cpp
$ valgrind ./prog
It will print very detailed error messages about memory access problems, with source code line numbers. If those still don't make sense to you, please post the full source code (prog.cpp) and the full output of valgrind.
I've run valgrind for you, its output is here: http://pastebin.com/J13dSCjw
It seems that you use some values which you don't initialize:
==21408== Conditional jump or move depends on uninitialised value(s)
==21408== at 0x8048E9E: main (prog.cpp:61)
...
==21408== Conditional jump or move depends on uninitialised value(s)
==21408== at 0x804A809: zero(int (*) [4], int (*) [4], int*, int, int, int, int, int, int) (prog.cpp:410)
==21408== by 0x804A609: lowest(int (*) [4], int (*) [4], int, int, int, int, int, int) (prog.cpp:354)
==21408== by 0x804932C: main (prog.cpp:125)
...
To fix these problems, add code which initializes the variables depicted in the error lines above (e.g. line 61, 410), then recompile, and rerun with valgrind again, until all errors disappear.
If your program behaves weirdly even after fixing all problems reported by valgrind, please let us know.
Lines 57 - 67:
for (i=0; i<=4; i++)
{
for (j=0; j<=4; j++)
{
if (cur[i][j] == 0)
{
row = i;
col = j;
}
}
}
at least one of your errors is in this code, cur is declared int cur[4][4]; this means then when j==4 (and when i==4) you are not within the bounds of your array (well you are within the memory for some of them, but not all) valid values will be 0 - 3.

Eigen Jacobi causing odd segfault in c++

So I have the following lines in my code:
MatrixXd qdash = zeroCentredMeasurementPointCloud_.topLeftCorner(3, zeroCentredMeasurementPointCloud_.cols());
Matrix3d H = q * qdash.transpose();
Eigen::JacobiSVD<MatrixXd> svd(H, Eigen::ComputeThinU | Eigen::ComputeThinV);
Now I am sure that qdash and H are being initialised correctly (q is also, just elsewhere). The last line, involving Eigen::JacobiSVD causes the program to throw this error when it is left in:
Program received signal SIGSEGV, Segmentation fault.
0xb0328af8 in _list_release () from /usr/qnx650/target/qnx6/x86/lib/libc.so.3
0 0xb0328af8 in _list_release () from /usr/qnx650/target/qnx6/x86/lib/libc.so.3
1 0xb032a464 in __free () from /usr/qnx650/target/qnx6/x86/lib/libc.so.3
2 0xb0329f7d in free () from /usr/qnx650/target/qnx6/x86/lib/libc.so.3
I.E. it is seg-faulting when trying to free it i guess. Now according to the tutorial here, all I should have to do to use this functionality is this:
MatrixXf m = MatrixXf::Random(3,2);
JacobiSVD<MatrixXf> svd(m, ComputeThinU | ComputeThinV);
Can anyone see why it is failing in my case?
Ok so this is super crazy. Turns out I was using Eigen Alignment which doesnt really work on my operating system. This caused an error which would change location just based on the size of the executable that was produced.
The moral of the story is be careful with your includes.