C++, process stops in Console Application - c++

Hi I am using Codeblocks and a problem occurs when I start this program:
int number_STABLE= 2;
int number_VARIABLE;
int numberof_STEPS = 0;
void Check() {
number_VARIABLE=number_STABLE;
while (number_VARIABLE!=1) {
if (number_VARIABLE%2!=0) {
number_VARIABLE=(number_VARIABLE*3)+1;
} else {
number_VARIABLE=number_VARIABLE/2;
}
numberof_STEPS++;
}
}
int main()
{
cout<<" - STARTED - "<<endl;
cout<<endl;
while (numberof_STEPS!=555) {
numberof_STEPS=0;
cout<<"Stable: "<<number_STABLE<<endl;
cout<<endl;
Check();
number_STABLE++;
number_VARIABLE=0;
cout<<"Steps: "<<numberof_STEPS<<endl;
cout<<endl;
}
cout<<"Number of steps: "<<numberof_STEPS<<endl;
cout<<endl;
cout<<"Last number: "<<number_STABLE-1;
return 0;
}
It runs for approximately two minutes then it stops. When closing the console app window this is the error message displayed in the Build log:
Process terminated with status -1073741510 (1 minute(s), 54 second(s))
Could someone explain why this happens and/or how can I prevent it?

First of all, these two lines are nonsense:
while (numberof_STEPS!=555) {
numberof_STEPS=0;
This loop will never exit.
Second: Do not use global variables as loop variables. Automatic variables are much faster because they will be put into a register. Incrementing the variable outside the function containing the loop makes it all worse because the program becomes totally incomprehensible.
Third: Your technical problem presumably is an integer overflow. The Collatz sequence rapidly reaches the 2^31 limit. Try this one:
int i;
i = 2147483647;
cout << i << endl;
i++;
cout << i << endl;

Related

Creating a simple crackme program in C++ problems with variable and input

So I am trying to learn C++ so I can learn some reverse engineering that why I am trying to create this simple crack me program to get a foundation going and not take someone else's project as I choose my own path. However I am using CodeBlocks as the other IDEs were not being cooperative and am enjoying it and has given me some error and two lines. Below is the following code. So there errors are the following:
||=== Build: Debug in SimpleProgram (compiler: GNU GCC Compiler) ===|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp||In member function 'int checker::processing(int)':|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp|15|warning: no return statement in function returning non-void [-Wreturn-type]|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp||In function 'int main()':|
D:\Programming\C++ Projects\simple programs\SimpleProgram\main.cpp|22|error: 'x' was not declared in this scope|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
#include <iostream>
using namespace std;
class checker{
public:
int number;
processing(int x){
x = number;
if ( number == 10 ){
cout << "Well done!";
} else {
cout << "Keep trying!";
}
}
};
int main()
{
checker cracking;
cout << "Please enter in the correct number";
cin >> cracking.processing(x);
return 0;
}
Image of the project and error
A function always has a return type, even if your not attempting to return anything it will have the void signature. If your intent was to take input of a number passed from main and display it via a function in your class checker through an object of the same, this is how it would look like:
#include <iostream>
using namespace std;
class checker{
public:
int number;
void processing(int x)
{
if (x==10)
cout << "Well done!";
else
cout << "Keep trying!";
}
};
int main()
{
checker cracking;
cout << "Please enter in the correct number \n";
int n;
cin >> n;
cracking.processing(n);
return 0;
}
I've cleaned the code up and included comments that serve as notes:
#include <iostream>
using namespace std;
class checker{
public:
void setnumber(int i){ //it's a good habit to put variables in private and access them with a public function
this->number = i;
};
int processing(int x){ //x is just a placeholder value for whatever you put in here. You can't use it in the rest of the program
if ( x == 10 ){
cout << "Well done!" << endl;
return 1; //this condition indicates success
} else {
cout << "Keep trying!" << endl; //the endline just makes it so you aren't typing on the same line as the message
return 0; //this condition indicates success hasn't been reached yet
}
}
private:
int number;
};
int main()
{
checker cracking;
cracking.setnumber(10); //the number is set to 10
int i, l; //i is the guess number, l is a condition for the loop
cout << "Please enter in the correct number" << endl;
do{ //this loop sets it up so that you can have multiple tries
cin >> i;
l = cracking.processing(i);
}while(l!=1); //and this condition (the return value of processing(), breaks the loop on success
return 0;
}
The main issue that popped out at me was the use of x.
Trying to set x to number. In functions, the parameters are just placeholder values for arguments that will be passed into later. Then later on when you tried to use x as an input in the main() program. You were calling that function (using it) and needed an int as input.
Don't worry. It's confusing in the beginning for everyone (although to be fair, as you progress you'll just find new things to be confused about. It never really stops). Keep at it and it'll all make sense in time.

Segmentation Fault during Debugging C++

So, have an assignment where I need to solve the N-Queens* problem using the stack.
*N-Queens problem: you have a chessboard with N rows/columns/queens. You must place each queen so that it cannot attack any of the others on the board.
I created a Queen class just to store the row and column positions for each valid queen placed, and that is working fine. As far as I can tell, all of my sorting and checking logic is also fine. However, either in main or my solve function, I'm getting a Segmentation Fault, but only when I debug. When ran normally, it just exits. My debugger unfortunately doesn't let me go line by line, but I've manually done so and still can't figure this out.
void solve(int k, int N)
{
stack<Queen> queenStack;
if(k == N)
{
while(!queenStack.empty())
{
cout << queenStack.top().rowPos << ", " << queenStack.top().colPos << endl;
queenStack.pop();
}//end while
}//endif
else
{
for (int i = 0;i < N; i++)
{
if (isSafe(k,i))
{
Queen queen(k,i);
queenStack.push(queen);
solve(k++,N);
}//end if
else
{
if(queenStack.empty())
{
break;
}//end if
else
{
queenStack.pop();
k--;
}//end else
}//end else
}//end for
}//end else
}//end void
then my main:
int main()
{
int N = 0;
cout << "Please pick an integer 3 or greater and less than whatever you think won't crash your computer." << endl;
cin >> N;
while (N < 3)
{
cout << "Please pick an integer 3 or greater and less than whatever you think won't crash your computer." <<
endl;
cin >> N;
}//end while
solve(0,N);
return 0;
}//end main
my ifSafe is a bool function that just does checks based on row, which I pass in as an int, and then return the true/false for the loop.
First of all, there's an obvious issue in your code that will immediately lead to a stack overrun. The way you recursively call your solve function:
solve(k++,N);
Will first call solve, and then increment k. So solve(0, N) calls to solve(0, N), which in turn calls to solve(0, N) leading to stack overrun. There's no side effects or any external variables that would affect solve and make it behave differently with the same arguments.
I don't fully understand your solution, so I can't tell you how to fix it, but most likely your intent was for queenStack to be visible across the calls, in which case it would make sense to make it global, or to pass it into the solve by reference.
Now to why it finishes just fine when you run it outside of the debugger. My guess would be that you use some kind of non-windows system (mac or linux) and run it from the terminal. This way the program still crashes, but does not show it in any obvious way. The way to see if it finished successfully is to print $? after executing a program:
a#a-dev:~$ ./crash_me
a#a-dev:~$ echo $?
1
If the program executed normally, the return code should be zero.

loop in c++ that keeps track when the count is divisible by 4

Hello I am having trouble with a c++ program. Basically its a loop that iterates the amount of times the user wants it to. Now when it reaches a number divisible by 4 it keeps track of that number and finally then outputs how many times the number entered was divisible by 4.
#include<iostream>
using namespace std;
int num;
int count;
int test = 0;
int main()
{
cin>> num;
for (int count = 0; count < num; count++)
if (count % 4 == 0)
(test++);
else
cout<<"";
return 0;
}
Well - if you use return in main, your program will just exit, because that's what return does - ends the function and returns some value. If you want to actually print the value of test, do it before you return:
cout << test;
getch(); // use this so the console won't close automatically
return 0;
Also, the whole program could be written much better:
int main()
{
cin>> num;
cout << num/4;
getch(); // use this so the console won't close automatically
return 0;
}
Do you need to use a loop? If you just need "How many times is a given number divisible by 4" and are not required to loop
#include<iostream>
using namespace std;
int main()
{
int num;
cin>> num;
cout<< num<<" is divisible by 4 "<< (num>>2) <<" time"<<(num>>2>1?"s":"") <<endl;
return 0;
}
num>>2 is bit shifting to teh right twice, which is the same as doing an integer divide by 4. It could be replaced by num/4 if you wanted. Integer division always truncates, so for all positive numbers, it's like rounding down: the same behavior your loop gives you.

Making an if condition return if its true or while return if its true

When the condition is true or false, how can I make it return back and ask the question again, making the user re-enter the value?
Here is what I want to implement:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
bool tr=true;
while(tr)
{
if(n!=5)
cout<<"You entered "<<n; //How to make it return again, since its false? I keep getting infinite loops :( ;
else
tr=false;
}
return 0;
}
You need to prompt the user in the while loop, so that it occurs in each iteration:
int n;
bool tr = true;
while(tr)
{
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n!=5) {
cout << "You entered " << n;
} else {
tr = false;
}
}
Just put all your code (except 'n' and 'tr' definition) in while loop as follow:
int main()
{
int n;
bool tr=true;
while(tr)
{
cout<<"Enter numbers. Press 5 to stop: ";
cin>>n;
if(n!=5)
cout<<"You entered "<<n;
else
tr=false;
}
return 0;
}
The other answers all work, and there is something to be learned about improving program flow from them, but I believe the trick you're asking for is the continue keyword, which skips the remainder of this iteration of the loop.
bool tr = true;
int n;
while (tr)
{
cout << "Enter numbers...";
cin >> n;
if (n != 5)
continue;
else
tr = false;
}
EDIT Part 1: On the continue keyword.
You want to make your code as readable as possible. In this example, its use is unnecessary (as the other posters have shown); but it is the answer to the question "How do I skip the rest of processing in this iteration of my loop and continue to the next iteration?". Usually, such flow-breaking directives actually make code harder to read; but sometimes the opposite is true. Anything (or, at least, almost anything) that can be accomplished with continue or break, can be accomplished without them, so if you're going to use them, you want to have a definite reason for doing so. Usually, when I use continue, it's because I'm looping through a collection of inputs and I want to skip processing the loop whenever the input isn't in the format I'm expecting. Something like this (pseudo-code)...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
{
cout << "Bad input";
continue;
}
// Do massive block of calculating here.
}
is easier to read than this...
foreach (Input i in ReceivedInputs)
{
if (i.isBad())
cout << "Bad input";
else
{
// Do massive block of calculating here.
}
}
because the second version makes it harder to track what scope you're in, if you're looking toward the end of the massive block of calculating. In this case, I gain code readability by continue, so I use it. But simple code probably shouldn't use it. The break keyword is similar, though it's a lot easier to come up with examples where break is beneficial.
EDIT Part 2: On multiple iterations
This is just an issue of setting up the loop; there are no magic keywords here. The shortest way I can come up with, is probably something like this:
int n = 0;
int numberToTake = 10;
for ( int numbersTaken = 0; numbersTaken < numberToTake; ++numbersTaken)
{
cout << "Enter numbers...";
int n = 0;
for (cin >> n; n != 5; cin >> n)
cout << "Try again.";
// Do whatever processing on n you want to do here.
}
Though I should point out that, doing it this way, the only value you will ever get from the user will be 5, and if he inputs anything that doesn't fit in an integer, you will get unexpected behavior.
EDIT 3: After reading the comment more thoroughly, I think you're just looking for is the more traditional use of the for loop.
No need for the exra bool variable.
The idiom can be: Infinitely loop until the user enters 5:
for(;;) { // Loops infinitely
cout << "Enter numbers. Press 5 to stop: ";
cin >> n;
if(n == 5)
break; // Exits the loop
cout << "You entered " << n; // Before the if if you want to print 5 as well
}

c++ program gives an error" the value of 'i' is not initiated"

this code gives an error "i" is not initiated, can anybody help it out ?
the program complies easily. and at the time of running, every switch case works but 2.
#include<iostream>
using namespace std;
const int m=50;
class ITEMS
{
int itemCode[m];
float itemPrice[m];
int count;
public:
void CNT(void)
{
count=0;
}
void getItem(void);
void displaySum(void);
void remove(void);
void displayItems(void);
};
functions used.
void ITEMS :: getItem (void)
{
cout<<"entr itm cod";
cin>> itemCode[count];
cout<<"entr itm cost";
cin>> itemPrice[count];
count++;
}
the problem is here. this function"displaySum (void)" must give an output by summing the prices of all the items
void ITEMS ::displaySum (void)
{
float sum =0;
for (int i; i<count;i++)
sum+=itemPrice[i];
cout<<"\n total value"<< sum<<endl;
}
void ITEMS ::remove (void)
{
int a;
cout<< "entr itm cod";
cin>> a;
for(int i=0; i<count;i++)
if (itemCode[i] == a)
itemPrice[i]=0;
}
void ITEMS :: displayItems(void)
{
cout<< "\n Code price\n";
for(int i=0;i<count;i++)
{
cout<<"\n" << itemCode[i];
cout<<" " << itemPrice[i];
}
cout<< endl;
}
main function. this is here i called all the above functions. using the main function.
int main()
{
ITEMS order;
order.CNT();
int x;
do
{
cout<< "select any opt"
<<"\n 1. add"
<<"\n 2. display total valu"
<<"\n 3. delete an item"
<<"\n 4. display all"
<<"\n 5. quit?
<<"\n number ?";
cin>> x;
switch(x)
{
case 1: order.getItem(); break;
case 2: order.displaySum(); break;
case 3: order.remove(); break;
case 4: order.displayItems(); break;
case 5: break;
default: cout<< "try again";
}
}while(x!=5);
return 0;
}
In displaySum you have:
for (int i; i<count;i++)
sum+=itemPrice[i];
i is not initialized here. That's probably not what you want.
Also, make sure you pay attention to what your compiler tells you. If you are using gcc, for example, you can use the options "-Wall -Werror" which generates warnings for common programming mistakes, and reports them as errors. IMO this is good practice as it forces you to at least look at that spot to see if you actually made a programming error.
I don't know which compiler you're using, but I don't know of a single one that does not provide at least a line number when printing warnings. Use the resources available to you. The compiler almost certainly told you exactly what was wrong and where the error occured. While the expression you used is legal, it is certainly an error.
int i;
does not initialize the local variable, make an experiment and print it, you will see it is filled with previous stack junk. so it probably wont satisfy the for(;;) condition and just never enter the loop
use
int i = 0;
In displaySum you are not initializing variable i, so it contains a garbage value and your loop will behave unpredictably.