I’m working on a problem in C++, but I’m getting a stack overflow exception and I can’t tell why. The main method calls problem28(), but the first line should print “check” to my output, which isn’t happening. If I define gridsize as 501 or less it runs fine, but anything more than that and it throws a stack overflow exception.
Any help would be appreciated.
#define right 0
#define down 1
#define left 2
#define up 3
#define gridsize 1001
int* next(int row, int col, int dir) {
int* newPos = new int[2];
newPos[0] = row;
newPos[1] = col;
switch(dir) {
case right:
newPos[1] += 1;
break;
case down:
newPos[0] += 1;
break;
case left:
newPos[1] -= 1;
break;
case up:
newPos[0] -= 1;
break;
}
return newPos;
}
int problem28() {
cout << "check" << endl;
int grid[gridsize][gridsize];
for (int i = 0; i < gridsize; i++)
for (int j = 0; j < gridsize; j++)
grid[i][j] = 0;
int* pos = new int[2];
pos[0] = pos[1] = gridsize / 2;
int dir = right;
for (int i = 1; i <= 1001; i++) {
grid[pos[0]][pos[1]] = i;
pos = next(pos[0], pos[1], dir);
int* npos;
npos = next(pos[0], pos[1], (dir + 1) % 4);
if (grid[npos[0]][npos[1]] == 0)
dir = (dir + 1) % 4;
}
cout << "generated grid" << endl;
int total = 0;
for (int i = 0; i < gridsize; i++) {
total += grid[i][i];
total += grid[i][gridsize - i - 1];
}
total -= grid[gridsize / 2][gridsize / 2];
return 0;
}
int main() {
problem28();
system("pause");
return EXIT_SUCCESS;
}
Your stack is typically quite limited compared to memory overall. Since
problem28doesn’t seem to be recursive, by far the easiest fix that’s most likely to work is to change:to:
That will allocate the memory for that array statically instead of locally, which will typically mean it’s no longer on the stack.
Another possibility would be to use a
std::vectorinstead of an array. This will will normally allocate its memory from the free store instead of locally. The minor problem is thatvector(by itself) doesn’t provide 2D addressing, so you’d have to handle that separately (e.g., using the array_2D I posted in a previous answer).