A segmentation fault - c++

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...

Related

why infinite loop terminates? or go infinite

I was trying a test and I wrote this program...
#include<iostream>
using namespace std;
main()
{
int arr[5]={1,2,3,5,3}, num=5;
for(int i=0; i< num; i++)
{
for(int j=(i+1); i< num; j++)
{
if (arr[i]==arr[j])
{
cout<<"test";
}
cout<<j<<endl;
}
}
}
hmmm...
In the below code I know I used "i" instead of "j",So just to create the problem I used this
for(int j=(i+1); i< num; j++)
And my problematic part of the program is-
for(int j=(i+1); i< num; j++)
{
if (arr[i]==arr[j])
{
cout<<"test";
}
cout<<j<<endl;
}
in the above code when I remove this if block-
if (arr[i]==arr[j])
{
cout<<"test";
}
the program goes infinite.........
But when I put this if block again the program terminates automatically after some execution.
I also read about this on this link but it shows example of java
And there they show the reason of negative value, but in my program there is no garbage value comes.
The loop condition is never false. Hence the program will continue running indefinitely.
However, with if (arr[i]==arr[j]) you access outside the bounds of arr. Hence the behaviour of the program is undefined. When the behaviour of the program is undefined, it doesn't necessarily behave as you might expect. For example, it might not continue running indefinitely.
Even without if (arr[i]==arr[j]), the loop will eventually have undefined behaviour when the loop counter overflows. But a program with undefined behaviour doesn't necessarily behave as you might not expect. For example, it might continue running indefinitely.
Without the if (arr[i]==arr[j]), you simply have an infinite loop, which is perfectly valid in this case. j will just keep getting incremented (eventually this will overflow, which in undefined behaviour, see [basic.fundamental]/2), and the condition will never be met, since i does not change.
However, with the if (arr[i]==arr[j]) in the code, j is being incremented, and you will go outside the bounds of the array (as you know). In C++, this is Undefined Behaviour, meaning anything can happen. In your case, it seems to be causing the program to crash (which is actually a good thing, since it indicates an error).
I think, the problematic part of code is
for(int j=(i+1); i< num; j++)
You are increasing j while you are checking i< num.
If you replace it with
for(int j=(i+1); j < num; j++)
it might start working.
Why it is terminating with if block, and not terminating without if block
if (arr[i]==arr[j])
{
cout<<"test";
}
Because int have finite amount of possible values. When you reach the maximal value of int variable, the value + 1 is the smallest possible int. (As #user17732522 pointed out, the behavior might be utterly different - program crashing or something nasty happening here - because behavior of int 'overflowing' is undefined. Therefore your programs memory might be already corrupted here and it need to perform some operations to see it happened...eg. by program crash.)
Now, let's think about, what arr[i] does. arr is basically a pointer to a memory, where array begins and [i] operation is the same thing as *(arr + i).
Now, there are two possibilities what might happen
Program crashes when i is positive and outside of the array
Program crashes when i is negative
In both cases, the program crashes, because you are trying to access protected or nonexistent zone of a memory. This depends on the architecture of the system - Eg. In negative zone on 64 bit AMD64 system, you are clearly accessing nonexistent memory, if you don't have 16 exabytes of RAM. The program must in such case cause processor interruption, which is given to your OS, which kills your application.
Why it doesn't crashes when you delete the block? Nobody is trying to access the *(arr + j) and therefore, j is repeating from minimal possible value to maximal possible value without any problem.
The problem is this if statement will always be true:
for(int j=(i+1); i< num; j++){infinity}
Try setting it to this instead:
for(int j=(i+1); j< num; j++){not infinity}
You can't pass a loop on a statement that will not eventually return false or it'll go on forever.

Segmentation fault in c++ program using vector

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.

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.

If statement not executed slows program

I have an if statement that is currently never executed, however if I print something to the screen it takes over ten times longer for the program to run than if a variable is declared. Doing a bit of research online this seems to be some kind of branch prediction issue. Is there anything I can do to improve the program speed?
Basically both myTest and myTest_new return the same thing except one is a macro and one is a function. I am just monitoring the time it takes for bitTest to execute. and it executes in 3 seconds with just declaration in if statement but takes over a minute when Serial.print is in if statement even though neither are executed.
void bitTest()
{
int count = 0;
Serial1.println("New Test");
int lastint = 0;
Serial1.println("int");
for (int index = -2147483647; index <= 2147483647; index+=1000) {
if (index <= 0 && lastint > 0) {
break;
}
lastint = index;
for (int num = 0; num <= 31; num++) {
++1000;
int vcr1 = myTest(index, num);
int vcr2 = myTest_new(index, num);
if (vcr1 != vcr2) {
Serial1.println("Test"); // leave this println() and it takes 300 seconds for the test to run
//int x = 0;
}
} // if (index)
} // for (index)
Serial1.print("count = ");
Serial1.println(count);
return;
}
It is much less likely to be caused by a branch prediction (that branch prediction shouldn't be influenced by what you do inside your code) but by the fact that
{
int x = 0;
}
simply does nothing, because the scope of x ends at }, so that the compiler simply ditches the whole if clause, including the check. Note that this is only possible because the expression that if checks has no side effects, and neither does the block that would get executed.
By the way, the code you showed would usually directly be "compiled away", because the compiler, at compile time, can determine whether the if clause could ever be executed, unless you explicitly tell the compiler to omit such safe optimizations. Hence, I kind of doubt your "10 times as slow" measurement. Either the code you're showing isn't the actual example on which you demonstrate this, or you should turn on compiler optimization prior to doing performance comparisons.
The reason why your program takes forever is that it's buggy:
for (int index = -2147483647; index <= 2147483647; index+=1000) {
simply: at a very large index close to the maximum integer value, a wrap-around will occur. There's no "correct" way for your program to terminate. Hence you invented your strange lastint > 0 checking.
Now, fix up the loop (I mean, you're really just using every 1000th element, so why not simply loop index from 0 to 2*2147483?)
++1000;
should be illegal in C, because you can't increase a constant numeral. This is very much WTF.
All in all, your program is a mess. Re-write it, and debug a clean, well-defined version of it.

C++ Beginner - Simple block of code crashing, reason unknown

Here's a block of code I'm having trouble with.
string Game::tradeRandomPieces(Player & player)
{
string hand = player.getHand();
string piecesRemoved;
size_t index;
//Program crashes while calculating numberOfPiecesToTrade...
size_t numberOfPiecesToTrade = rand() % hand.size() + 1
for (; numberOfPiecesToTrade != 0; --numberOfPiecesToTrade)
{
index = rand() % hand.size();
piecesRemoved += hand[index];
hand.erase(index,1);
}
player.removePiecesFromHand(piecesRemoved);
player.fillHand(_deck);
return piecesRemoved;
}
I believe the code is pretty self explanatory.
fillhand and removepiecesfromhand are working fine, so that's not it.
I really can't get what's wrong with this :(
Thanks for your time
EDIT
OK, I found out where the program crashes. Added a comment to the above source code.
If the hand is empty, then this operation:
rand() % hand.size()
In the initializer of the for loop, will be attempting to perform a modulus by 0, which is essentially division by zero. That is your crash.
Add a test to make sure the hand is not empty before proceeding with the rest of the method.
stick a breakpoint into your for loop to give you a better idea of what's going on. I would bet that the for loop is going infinite and causing the program to hang.
On hitting the breakpoint, check your iterator variables and see if you can see anything out of the ordinary
Maybe you want to use
for (size_t numberOfPiecesToTrade = rand() % hand.size() + 1; numberOfPiecesToTrade > 0; --numberOfPiecesToTrade)
to make things clearer.
Edit:
If you run in debug mode, than wo don't you just debug? :)
This "not responding" message is afaik often caused by an infinite loop.
Edit2:
I don't know if i am correct, but could it be that in some cases you will miss the numberOfPiecesToTrade != 0 condition if the initialvalue of numberOfPiecesToTrade is 1? I'm not familiar with size_t though.