Basj Basj - 1 year ago 67
C Question

Why does this simple loop crash?

The following code crashes when compiled with MS VC 2013 Express (Windows 7, 64 bit computer):

#include <iostream>
#define N 1000*1000

int main()
float x[N];
int i;
for (i = 0; i < N; i++)
x[i] = (float) (rand() + 1) / RAND_MAX;

What is wrong? Is it a memory problem?

Answer Source

You're basically trying to allocate an array of 1000000 elements, which is simply too big. It's just too huge for programs stack space.

Result: Stack overflow.

Side effect: Undefined behavior, crash.

Solution: Allocate that array in heap. Take a pointer, allocate memory using memory allocator function and you may be able to get it going.

Though arrays are not pointers but for most of the cases, a replacement like (in C)

float * x = malloc(N * (sizeof *x)); // for simplicity, omitting obligatory free, 
                                     // success check, stdlib inclusion etc.

would work.

That said, the actual solution would be, re-plan the program design, normally you should not be needing an array that large, try to make the design more modular and process in parts, as and when required.