program doesnt enter if condition , gives segmentation fault - c++

the code is somewhat like
cin >> n // test cases
for( n times )
{
.....
for(;;)
{
getline(cin,inp) //inp is supposed to be +,-,*,\,0-9,if simply enter pressed program passes out of loop
for(;;)
{
if (inp[0] == '*')
{
do stuff...
}
if (inp[0] == '\')
{
do stuff...
}
if (inp[0] == '+') \\ this is where the problem occurs
{
do stuff...
}
.....
.....
}
}
return 0 ;
}
here is the actual code with some comments ,i have tried converting infix to postfix inn the program . here's my input and the problem...
>1 //1 test case
>3 //if condition as it should entered line 124
>inp[0] 3 //confirms 3 is inp[0]
>* //works as it should (if condn entered line 37)
>inp[0] *
>/ //works as it should
>inp[0] /
>+ //problem!! if condition not entered even though it should
//as inp[0] == '+' (line 61)
>inp[0] + //confirmation inp[0] is + right before if condition checked
>Segmentation fault (core dumped)
I tried my level best to explain the code and the problem briefly, i ask this question as the problem looks totally ambiguos to me , any explanation needed pls tell me .
Also , give any suggestion to debug problems like these , i have got such errors before and i cant everytime ask here. Give any reccomendation to an beginner->amatuer coder for solving such segmentation faults .
thanks and regards

General advice:
use breakpoints and other features provided by your ide to find your problem.
It's been decades since c++ was born, there won't be such bug.
diag:
for debug message, change cout<<"+ detected"; to cout<<"+ detected"<<endl ;. endl for flushing the buffer and put it to screen.
it do enters your if-condition and failed at
if (stk.top() == '*' || stk.top() == '/' && stk.size() != 0 )
if stk.top() succeed, of course stk.size() != 0. It's not empty.
if stk.empty() == true, stk.top() will try to get something from an empty stack and throws seg fault back.
and just few lines below this there's another if-statement with the same mistake:
else if (stk.top() == '-' && stk.size() != 0 )
I changed these line and code works for your input sequence 1 3 * / +.

Related

Infinite Loop When Using Function Return Value as a Statement [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 5 years ago.
Was making a small code for a text based game but i tried to do thinks a bit different than the tutorial sort of to test my understanding but i tried to get a function value to make a do while statement but it seems whether the statement false or true the code just keep looping infinitely im a beginner so pls if you have a time explain why the code is faulty and Thank you in Advance
The main function
int main() {
PrintIntroStart();
do {
PlayGame();
AskToPlayAgain();
} while (AskToPlayAgain() == true);
return 0;
}
the Bool Function
bool AskToPlayAgain(){
//Asking The Player Whether To Play Again Or Not
std::string PlayerResponse = "";
std::cout << "Do You Want To Play Again? (Yes/No)" << std::endl;
std::cin >> PlayerResponse;
if (PlayerResponse[0] == 'y' || 'Y')
return true;
else
return false;
}
Also, here you are asking twice to play again
do {
PlayGame();
AskToPlayAgain();
} while (AskToPlayAgain() == true);
this should be
do {
PlayGame();
} while (AskToPlayAgain() == true);
if (PlayerResponse[0] == 'y' || 'Y') this one should be
if (PlayerResponse[0] == 'y' || PlayerResponse[0] == 'Y')
Otherwise your if condition is always true, because 'Y' itself is non-zero.
And in fact you don't need this if statement, just
return PlayerResponse[0] == 'y' || PlayerResponse[0] == 'Y';
So first of all, you are only checking the outcome of the game every second play.
You should follow #ziza s answer and remove the function call inside the loop.
The second problem, that causes the infinite loop is your input check.
A bool value in c++ is not a single bit, but just anoter regular value that is evaluated as false if it is 0 and to true if it has any other value. In your case the first comparison will evauate to 1 if the player input is 'y' and the second part of the condition will be the value of the 'Y' character (which is not 0). So your condition will always be true like #liliscent stated.

Program works fine in Debug, but not in Release

I made a tic-tac-toe game which works good. Recently I decided to add a reset game feature.
Here is the part where I take input from user
void playerMove() //Gets the player move and updates the box variables
{
int boxnumber;
while(1) //Set's loop if the player enters a invalid input
{
cout << "\n Player " << player << "'s turn!(Press 0 to reset the game!): ";
cin >> boxnumber;
if(box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0) // Checks if the input is valid or not
{
system("CLS");//If invalid, show error and loop back to start to get new input
displayBoard();
cout << "\n Invalid Input! Try again!\n";
}else if(boxnumber == 0)
{
refreshGame();
displayBoard();
}else
{
box[boxnumber-1] = player;//If inputs are fine, set the box variable's and break out of loop!
break;
}
}
}
Now, in debug mode, when I press 0, everything runs fine and the game is reset, but in release build, when I press 0, it gives me the "Invalid Input! Try again!"
Things I have tried the didnt work:
-Rebuild the entire release and debug version.
-Making a new project and copy-pasting my code. Same thing, debug works, release doesnt.
For anyone wondering, I am using code::blocks IDE. The compiler is GNU GCC.
Thanks for the help! :)
You have undefined behavior.
In the "first" if you have box[boxnumber-1], so when you enter 0 (as you have stated in your question), you're trying to access element with index -1. That's UB, as you're reading "invalid" memory.
You should check for 0 first (and for negative numbers also).
In the if statement, put the range checks in front of the value checks. That is, change
if(box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0)
to
if(boxnumber < 0 || box number > 9 || box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O')
That takes advantage of short-circuiting: if the input value is less than 0 or greater than 9 the value checks won't be executed. That will avoid checking things like box[10], which isn't valid.
That still leaves a problem: if the user inputs 0, this code will happily check box[-1], which is also out of range. To get rid of this, move the branch of the if statement that tests box number == 0 in front of this part:
if (box number == 0)
// whatever
else if (box[boxnumber-1] == 'X' || box[boxnumber-1] == 'O' || boxnumber > 9 || boxnumber < 0)
// whatever else

if condition on turbo C++

I'm having a problem regarding with if statement in C++ this statement is in do-while loop.
gotoxy(27,22);cout<<"Do you want to continue [Y]?";
sub=getche();
if(sub!='y' || sub!='Y')
{
gotoxy(27,24);cout<<"INVALID ANSWER!!";
gotoxy(27,26);cout<<"Closing Program....";
delay(3000);
exit(1);
}else
{
sub=ans;
}
}while(tolower(ans)=='y');
whenever I input y on the variable sub the code on if statement is still executing.. please someone tells me where is the error.. Thanks!
The boolean expression of (sub!='y' || sub!='Y') will always evaluate to true
This line:
if(sub!='y' || sub!='Y')
Needs to be this:
if ( (sub != 'y') && (sub != 'Y') )
Your code if(sub!='y' || sub!='Y') will be true ,no matter what you enter because eithersub!='y' or sub!='Y' will evaluate to true. Hence Use && instead of ||.

OpenCL Out of Resources - Crash at code line which is not reached at that moment

i'm doing some OpenCL programming and at one location in my code I get strange error.
a and a_end are pointers to local memory
if (a+POS<=a_end) {
max = ....
} else {
max = *(a_end-1);
}
In my case "else" isn't reached in the current loop. However, the application crashes with -5 CL_OUT_OF_RESOURCES if the line is part of the code.
If I comment the line the program works well. This is very strange.
Do you have any suggestions?
Regards,
Chris
Edit: Some more code
Values of a, a_end and POS1 before it crashes:
a: 3298304
a_end: 3311264
POS1: 34
border=b-b_end; //TODO: Check if all dummy elements are removed in this case
if(POS1<border && a+POS1<a_end) {
s_data[POS1+s_maxes[2]-border+1]=a[POS1];
s_ids[POS1+s_maxes[2]-border+1] = a_pos+POS1;
}
if(POS1+1==border) {
debug[0] = a+POS1;
debug[1] = a_end;
s_maxes[1]=*(b_end-1);
if(a+POS1<=a_end) {
s_maxes[0]=s_data[s_maxes[2]];
} else {
s_maxes[0]=*(a_end-1); //Here is the line where it crashes
}
}
if(POS2<border && a+POS2<a_end) {
s_data[POS2+s_maxes[2]-border+1]=a[POS2];
a_pos+POS2;
}
if(POS2+1==border) {
s_maxes[1]=*(b_end-1);
if(a+POS2<=a_end) {
s_maxes[0]=s_data[s_maxes[2]];
} else {
s_maxes[0]=*(a_end-1);
}
}
a+=border;a_pos+=border;
There is a good chance that the following scenario happens: before your if the value of a_end is corrupted, highly possibly it gets initialized to 0 (without further knowledge of the code this is my best shot, but it also might be a value which is smaller than a + POS) and then obviously the else branch gets executed which tries to de-reference the value found at address 0 - 1 which is a pretty big number and then the application crashes. Obviously if you remove the else branch this code is not executed.
Hint: Put some printouts for the value of a_end.

expected primary-expression before 'else'

I have an emergency here. This homework is due tomorrow for my CP 1 class. We have to make a simple dice game. If you get doubles of the same number, then good things happen. Here is the function:
void Doubles(); //prototype for the function Doubles()
//pre: n/a
//post: Plays a simple dice game with the user
void Doubles()
{
//variables declared to store dice values
int DieOne, DieTwo, PlayerSame, ComputerSame;
cout<<"\nLET'S PLAY DOUBLES!!!\n"<<endl;
srand ( time(NULL) ); //initialize random seed
DieOne = rand()%6 + 1;
DieTwo = rand()%6 + 1;
cout<<"\nYour first die is a "<<DieOne;
cout<<"\nYour second die is a "<<DieTwo;
if(DieOne == DieTwo)
{
PlayerSame = 1;
}
else
{
PlayerSame = 0;
}
DieOne = rand()%6 + 1;
DieTwo = rand()%6 + 1;
cout<<"\n\nThe computer's first die is a "<<DieOne;
cout<<"\nThe computer's second die is a "<<DieTwo;
if(DieOne == DieTwo)
{
ComputerSame = 1;
}
else
{
ComputerSame = 0;
}
if(PlayerSame == 1 && ComputerSame == 0)
{
cout<<"\n\nYou win! Your dice are the same and the "
<<"computer's dice aren't!";
}
else if(PlayerSame == 1 && ComputerSame == 1)
{
cout<<"\n\nYou tied! Your dice are the same and the "
<<"computer's dice are the same!";
}
else if(PlayerSame == 0 && ComputerSame == 1)
{
cout<<"\n\nYou lost! Your dice are not the same, and the "
<<"computer's dice are!";
else
{
cout<<"\n\nNeither you nor the computer had dice that matched, "
<<"so you both lose!";
}
}
So why, wen I run this, am I getting the compiler error stated in the title? the primary expression is right there! The "else" it's referring to is the last one there. Any help is greatly appreciated.
You are missing the brace, as has been pointed out, but the flaw comes from not being able to look at the code indentation correctly and not being able to clearly see the error. The indentation on the else if's is indented one more than the if, and if this were not the case, you would quickly see the missing brace, but, as formatted, it is more easily missed, although I did not even read the whole post before looking at the code and spotting the missing brace myself (I have a lot of legacy code which I maintain that has bad indentation that I have been fixing for years, and this is a common type of formatting error that leads to this specific problem.. Proper formatting would lead to the spotting of this type of error much more quickly, especially in programmers that have not been programming for a long time and are not seasoned to fix the formatting in their head as they read through before looking at code specifics.
Jay
you forgot the closing brace for the block after the second else if
Looks like you are missing a brace } after <<"computer's dice are!"; line.
Doesn't your compiler tell you the line number where it sees the error?
PLease add the closing brace before the else.
else if(PlayerSame == 0 && ComputerSame == 1)
{
cout<<"\n\nYou lost! Your dice are not the same, and the "
<<"computer's dice are!";
}
else
{
cout<<"\n\nNeither you nor the computer had dice that matched, "
<<"so you both lose!";
}