I'm getting a stack overflow exception in C++ program - c++

I am getting a system.stackoverflowexception.
I think it is happening somewhere inside the insert() function.
void insert(char* word){
int r1 = rand()%x; // Here is where I suspect the problem starts
int c1 = rand()%x;
if(gameBoard[r1][c1]=="") {
gameBoard[r1][c1] = word;
insertWordCopy(word);
} else
insert(word);
}

The following is incorrect, since it compares the pointers:
if(gameBoard[r2][c2]=="") {
As a result, the code almost certainly always goes down the else branch, resulting in infinite recursion.

Related

How do I fix this runtime error related to div by zero?

Here is the chunk of code in question that I've pulled from my program:
#include <vector>
using namespace std;
vector<double> permittingConstructionCosts(56);
static const int PERMITTING_PERIODS = 0;
static const int CONSTRUCTION_PERIODS = 11;
static const double CONSTRUCTION_COSTS = 2169506;
static const double PERMITTING_COSTS = 142085;
static const int PERMITTING_CONSTRUCTION_PERIODS = PERMITTING_PERIODS + CONSTRUCTION_PERIODS;
void calcExpenses // Calculates permitting and construction expenses
(
vector<double>& expense,
double value1,
double value2
)
{
int i;
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
for (i=PERMITTING_PERIODS + 2; i<expense.size(); i++)
{
if (i < PERMITTING_CONSTRUCTION_PERIODS + 2)
{
expense[i] = value2;
}
}
}
int main()
{
if (PERMITTING_PERIODS != 0)
{
calcExpenses(permittingConstructionCosts, -PERMITTING_COSTS/PERMITTING_PERIODS, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
else
{
calcExpenses(permittingConstructionCosts, 0, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
return 0;
}
According to ideone (http://ideone.com/LpzUny) the code has a runtime error that returns "time: 0 memory: 3456 signal:11".
I've tried to look for solutions on SO and found the following links:
How can I avoid a warning about division-by-zero in this template code?
How to eliminate "divide by 0" error in template code
However, I don't know how to use templates because I am new to c++ and I'm not sure I need to use them in this case so I have no clue how to adapt those solutions to my particular problem if it's even possible.
I'm pretty sure that the "-PERMITTING_COSTS/PERMITTING_PERIODS" is causing the problem but I thought that simply checking the divisor would solve the problem. This function seems to work for every other value other than 0 but I need to account for the case where PERMITTING_PERIODS = 0 somehow.
I would very much appreciate any help I can get. Thanks in advance!
Edit: I actually do initialize the vector in my program but I forgot to put that in because the size is decided elsewhere in the program. The chunk of code works once I fix that part by putting in a number but my program still has a runtime error when I set PERMITTING_PERIODS to 0 so I guess I have to go bug hunting elsewhere. Thanks for the help!
The problem lies inside the function, which is called by the else statement in the main function:
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
Here, PERMITTING_PERIODS is 0, thus you loop from 0 to 2 (inclusive).
However, expense.size() is 0, since your vector is empty. As a result, you are trying to access an empty vector, which causes a segmentation fault.
With that said, print the value of i inside the loop, you should see that you try to access expense[0], but the vector is empty, so it has no first slot (basically it doesn't have any)!!
So replace that with:
expense.push_back(value1);
which will allocate enough space for your values to be pushed into the vector.
The answer given in the cited links, (i.e. "How to eliminate "divide by 0" error in template code") applies equally well here. The other answers were given in the context of templates, but this is completely irrelevant. The sample principle applies equally well with non-template code, too. The key principle is to compute a division, but if the denominator is zero, you want to compute the value of zero instead of the division.
So we want to compute -PERMITTING_COSTS/PERMITTING_PERIODS, but use the value of 0 instead of the division when PERMITTING_PERIODS is 0. Fine:
int main()
{
calcExpenses(permittingConstructionCosts,
(PERMITTING_PERIODS == 0 ? 0: -PERMITTING_COSTS)/
(PERMITTING_PERIODS == 0 ? 1: PERMITTING_PERIODS),
-CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
return 0;
}

1D Peak, on execution says an error has caused the code to be stop working

I am trying to find the 1D peak through Divide and Conquer technique in this particular question,
my program even though it runs,
but at the time of giving the final output it says that there has been some problem with the execution,
I have got the answer from a different method, but I would like to know where am I at fault here.
#include<iostream>
using namespace std;
int a[8];
class pg1
{
public:
int func(int n)
{
if(a[n] <= a[n+1])
{
func(n++);
}
else if(a[n] <=a [n-1])
{
func(n--);
}
else
{
return n;
}
}
};
int main()
{
pg1 ob;
for(int i=0;i<8;i++)
{
cin >> a[i];
}
int x = ob.func(4);
cout << endl << x;
return 0;
}
Input-
5
6
8
5
4
3
6
4
Errors are-
1D Peak.exe has stopped working.
A problem caused the program to stop working correctly.Windows will close the program and notify you aif a solution is available.
End Result-
Process Exited with return value 3221225725
Don't use postincrement and similar in function calls.
Here's the problem condensed down to a really simple piece of code
#include <iostream>
int test(int n){
if(n == 1){
std::cout << "Function called!";
return test(n++);
}else{
return 0;
}
}
int main() {
test(1);
return 0;
}
Before you run this, ask yourself what you expect to happen here. Did it do what you thought?
When you run this you'll see that the code doesn't terminate properly. The output shows the function gets called infinitely many times, eventually the stack runs out of space and the program crashes.
You can see this code in action here: http://ideone.com/QL0jCP
In your program you have the same problem:
int func(int n)// say n = 4
{
if(a[n] <= a[n+1])//say this is true
{
func(n++); //this calls func(4) THEN increments n afterwards
}
This calls func with the same value over and over.
The solution is to not use postincrement or postdecrement in your function calls. These create hard to diagnose bugs as you have seen in this question. Just a simple func(n+1) is all you need. If you needed to use the variable later then just create an explicit variable to do that, it's much cleaner coding style (as this problem you ran into here shows).
After you fix this you'll need to fix your array bounds checking.
if(a[n] <= a[n+1])
If n is the last spot in the array you suddenly are trying to access one place past the end of the array, if you are lucky you get a segfault and a crash, if you are unlucky you get some bug that messes up your system that is hard to find. You want to check the values are valid.

Mysterious segmentation fault on function return with no pointers or allocation involved

I am currently writing some C++ code that does a lot of text parsing. One feature pushes chars into a string after checking if the char is a visible char (as opposed to whitespace). However, when I run the code below:
void myWords::pushChar(char c){
myChar cc;
std::cout<< "before if" <<std::endl;
if(!(cc.isWS(c))){
std::cout<< "after if" <<std::endl;
myList.back();
}
else if((myList.back()).size()>0){
myList.push_back("");
}
}
Which calls the following code block:
bool myChar::isWS(char c){ // returns true if char is whitespace
std::cout<< "comparing" <<std::endl;
if((c >= '!') && (c <= '~')){
std::cout<< "compared" <<std::endl;
return false;
}
else {
std::cout<< "compared" <<std::endl;
return true;
}
}
When these functions run, I (sometimes) get a segmentation fault immediately after the "compared" is printed by myChar::isWS(). There are no pointers/dereferences in my code (although I assume C++ implements STL containers with some pointing behind the scenes), and there is no memory accessing at that point aside from the return call. I ran Valgrind with the code, which has told me that there is an invalid memory access taking place.
What types of things could cause this kind of issue with no pointers/dereferences? Is there some way I could have corrupted the stack with that code?
Thank you in advance for your help.
Your error looks like you are calling size on non-existent object returned when you have an empty list. I.e in the second if statement. You need to check for an empty list before you can use back () safely.
I am guessing you want to something like this
void myWords::pushChar(char c)
{
if( !isWhitespace (c) )
{
myList.push_back(c);
}
else
{
if( !myList.empty() && (myList.back().size()>0) ) // is last element a non-empty string ?
{
myList.push_back(""); // then push an empty string on to list
}
}
}
It would be helpful to know how myList is declared and what the intended logic is in pushChar.

infinite loop in stack implementation c++

this is my first data structure program. I am implementing a simple stack using array with push, pop and initialize functions. I am getting an infinite loop as the output. Could you please tell me why is this so?
#include<iostream>
using namespace std;
# define SIZE 6
class stack{
public:
void init();
void push(int i);
int pop();
int top;
int stck[SIZE];//bydefault private
};
void stack::init()
{
top=0;
return;
}
void stack::push(int i)
{
if(top==SIZE)
{
cout<<"stack is full";
return;
}
else
{
top=top+1;
stck[top]= i;
return;
}
}
int stack::pop()
{
if(top==0)
{
cout<<"stack is empty. \n";
return 0;
}
else
{
top = top-1;
return(stck[top-1]);
}
}
int main()
{
stack stack1;
stack1.init();
int a;
int m;
while(a!=4)
{
cout<<"1. push 2. pop 3.display 4.exit .\n";
cin>>a;
if(a==1){
cout<< "enter value";
cin>>m;
stack1.push(m);
}
if(a==2)
{
cout<<"popped"<< stack1.pop();
}
if(a==3)
{
for(int k=0; k<=stack1.top;k++)
{
cout<<stack1.stck[k];
}
}
}
}
You never initialize a, so your program has undefined behaviour. Specifically, the while (a != 4) line performs an lvalue-to-rvalue conversion of a while its value is indeterminate, which the C++ standard explicitly states as undefined behaviour in section 4.1.
However, I doubt this is causing the issue at hand. In practice, unless the optimizer just optimized all your code out, your program should usually behave as expected; it's only when a == 4 on the first loop that you have problems. This doesn't make the code acceptable, but there's probably more to it.
I suspect the problem is that you use top to represent one past the number of elements. When you have zero elements, you point to the first; when you have one, you point to the second, etc. This means you're pointing to the first unused element.
However, in both your push and pop functions, you change top first and only then access the stack, but acting as if you didn't change it:
top = top + 1;
stck[top] = i;
When your stack is empty, this will set top to 1 and then access stck[1]. Meanwhile, stck[0] is left unset. When popping, you have the opposite:
top = top - 1;
return stck[top-1];
This sets top back to 0, but returns stck[-1], which is out of bounds.
I suspect that if you push SIZE values onto the stack, you will end up overwriting unrelated memory, which could cause all kinds of trouble. I still don't see how an infinite loop will follow, but given the behaviour is undefined, it is certainly a possible result.
(The alternative is that you at some point enter something other than a number. Seeing as you never check whether your input succeeded, if a != 4 and you enter something invalid, all further reads will fail, and a will remain unequal to 4. You could fix this by making changing your while to be
while (a != 4 && std::cin)
In that case, if you enter something invalid and std::cin goes into a non-good state, your loop (and thus program) will end.)
You only have a single loop, terminated based on user input.
If cin>>a fails, a will have whatever value it started with (undefined in your code), and you will loop on that unchanging value.
Typical ways for the input call to fail include
pressing control+D (on a *nix system)
pressing control+Z (on a Windows system)
redirected input from a pipe or file which is exhausted
There may be other causes of failed input as well.

What's wrong with my recursive function?

So I'm trying to implement a recursive function that generates the entire game tree of Tic-Tac-Toe, and I can't seem to get it to work.
void BuildTree(Node& nNode, const int& nextPlayer)
{
//Copy last board
Ticboard tBoard = nNode.m_board;
do
{
//Return first valid move
int validMove = tBoard.FirstValidMove();
if (validMove != -1)
{
Node f;
Ticboard tempBoard = nNode.m_board;
tempBoard.Move(validMove, nextPlayer);
tBoard.Move(validMove, nextPlayer);
f.m_board = tempBoard;
f.m_winCount = 0;
nNode.m_branches.push_back(f);
int currPlay = (nextPlayer == 1 ? 2 : 1);
BuildTree(f,currPlay);
}
else
{
break;
}
}while(true);
}
The actual function works, I've gone through and debugged it and it SHOWS it working as it is supposed to, but when I look at the nodes generated (for Tic-Tac-Toe, by the way) in Visual Studios via breakpoint, it only shows the first 9 branches. I know more were generated because it takes a few seconds, and I added a counter.
Here's how I call the code:
Ticboard lol;
Node startTree;
startTree.m_board = lol;
int startPlay = 1;
BuildTree(startTree, startPlay);
Without copying all my code for bitboards and whatnot in here, can you see anything immediately wrong with the logic?
nNode.m_branches.push_back(f);
This will push_back a copy of the Node f, so the stuff inside nNode.m_branches will be irrelevant to the modification of f later on.