Reputation: 571
I'm a beginner in C++ and don't understand many of background processes such as how compiler allocates memory etc. I'm using Visual Studio 2013 for writing c++ program. I have to use visual studio as I'm linking matlab to my c++ code.
I am getting stack overflow error which I don't know how to remove it. I don't get this error when I set N = 100, but when I set larger values of N such as 150, 200, I get the stack overflow error.
It will be really great if anyone can point out why I'm getting this error in VS. I tested the same code using codeblocks with GCC compiler which doesn't give any error at all.
#include<iostream>
using namespace std;
const int N = 200; //Number of grid points
int main()
{
double n = N;
double dx = 4 / (n - 1); double dy = 4 / (n - 1);
double col = n, row = n;
double dt = 0.5*dx; // time step size(dTau)
int itmax = 2500; // max iterations
int i, j, t;
double x[N] = { 0.0 }, y[N] = { 0.0 };
x[0] = -2; y[0] = -2; // define grid
for (i = 1; i < N; i++){
x[i] = x[i - 1] + dx;
y[i] = y[i - 1] + dy;
}
// Initialize variables
double phi_0[N][N], phi_new[N][N], F_0[N][N], F_new[N][N], F[N][N],
Fext[N][N], phi[N][N];
return 0;
}
Upvotes: 2
Views: 8824
Reputation: 490098
By default, Visual Studio creates a stack that's only a few megabytes (or maybe only one--I don't remember exactly, but typically only a small fraction of the memory on a current machine anyway). When N gets too large, you're just using more than that.
One obvious alternative is to define your large arrays as static
so they won't be on the stack.
static double phi_0[N][N], phi_new[N][N], F_0[N][N], F_new[N][N], F[N][N],
Fext[N][N], phi[N][N];
This forces the arrays to be allocated statically. In main
this makes little real difference, because main
isn't allowed to be called recursively. In a function that was directly or indirectly recursive, however, this could/would cause a problem. In such a case, you'd probably want to use an std::vector
instead, as this allocates (most of) its data on the free store and uses only a small, fixed amount of stack memory (typically around 12-32 bytes per vector).
Upvotes: 4
Reputation: 32884
You're allocating 7 double [N][N]
variables with automatic storage duration i.e. on stack. A single double variable is of size 64-bits (usually) i.e. 8 bytes; so in total 8 * 200 * 200 * 7 = 2240000 bytes (2.13 MiB) are required. This is probably more than the stack space allowed for a frame on your platform.
MSDN says that the default stack size is 1 MiB while you're trying to allocate more than that, hence the error.
Apart from the alternative that Jerry suggests, you also have the option of dynamic, free-store (usually on the heap) allocation, which is not limited by the stack size.
Upvotes: 1