0

I have a very simple for loop to generate some random float numbers:

int dim = 6;
int n = 100000;

int size = n * dim;

float data[size],r;
for(int i = 0; i < size; i++)
{
    r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
    data[i] = r;
}

It works fine until i increase the size of the n from 100000 to 1000000. Here is the full code on ideone: http://ideone.com/bhOwVr

Actually on my computer it works only with n=10000. Any bigger number causes a crash. No error message.

user1930254
  • 1,251
  • 5
  • 17
  • 32
  • 2
    You're probably running out of memory. – AndyG Jan 05 '15 at 15:52
  • 1
    You are trying to allocate an array on the stack which is too big for the stack here: `float data[size]` – sjdowling Jan 05 '15 at 15:53
  • AndyG i have plenty of memory. More then 4GB. If my math correct and a float 32bit = 4byte * 1 000 000 * 6 = 24 000 000 byte = 23437 kByte = 22 MB. – user1930254 Jan 05 '15 at 16:03
  • 1
    But you probably only have about 1MB of space on the stack, see my answer here: http://stackoverflow.com/questions/27189954/what-is-the-maximum-allowed-size-of-an-unsigned-char-array-in-visual-c-6-0/27190107#27190107 – sjdowling Jan 05 '15 at 16:05

1 Answers1

2

If you declare a fixed size array it will be allocated on stack. Stack memory of the program is quite limited. Here are some examples for default values. Also a relevant read: What and where are the stack and heap?

You can either increase stack size... Not recommended but works:

[luk32@localhost tests]$ g++ ./stack_mem.c 
[luk32@localhost tests]$ ./a.out 
Segmentation fault (core dumped)
[luk32@localhost tests]$ ulimit -s 32768
[luk32@localhost tests]$ ./a.out 
[luk32@localhost tests]$ #it worked.

Or dynamically allocate memory on heap:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    srand ( time(NULL) );

    int dim = 6;
    int n = 1000000;

    int size = n * dim;

    float *data,r;
    data = new float[size];
    for(int i = 0; i < size; i++)
    {
        r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
        data[i] = r;
    }
    delete[] data;
    return 0;
}

Result:

[luk32@localhost tests]$ g++ ./stack_mem.c 
[luk32@localhost tests]$ ./a.out 
[luk32@localhost tests]$ 

Although, after all I would recommend to use c++ features such as vector and randoms.

Community
  • 1
  • 1
luk32
  • 15,812
  • 38
  • 62
  • 2
    I think you should use `std::vector` in your example, particularly since yourself recommend it. – rodrigo Jan 05 '15 at 16:07
  • I just wanted to correct OPs code with as little changes as necessary. It would be closer if I made it proper c code. To do proper c++ I would need to rewrite almost whole program, which I feel goes way beyond the scope of the question. I am not feeling adventurous enough at the moment. – luk32 Jan 05 '15 at 16:10