2015-01-05 28 views
0

我有一個非常簡單的隨機浮動的for循環,產生一些隨機浮點數:產生for循環

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; 
} 

,直到我從100000〜1000000這裏增加n的大小它工作正常,是全代碼在ideone上:http://ideone.com/bhOwVr

實際上在我的電腦上,它只適用於n = 10000。任何更大的數字都會導致崩潰。沒有錯誤信息。

+2

您可能內存不足。 – AndyG

+1

你正試圖在堆棧中分配一個數組,這對堆棧來說太大了:'float data [size]' – sjdowling

+0

AndyG我有足夠的內存。超過4GB。如果我的數學正確並且float 32bit = 4byte * 1 000 000 * 6 = 24 000 000 byte = 23437 kByte = 22 MB。 – user1930254

回答

2

如果聲明一個固定大小的數組,它將被分配到堆棧上。程序的堆棧內存非常有限。 Here are some examples for default values。另外一個相關閱讀:What and where are the stack and heap?

您可以增加堆棧大小...不推薦,但工作原理:

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

或者在堆上動態分配內存:

#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; 
} 

結果:

[[email protected] tests]$ g++ ./stack_mem.c 
[[email protected] tests]$ ./a.out 
[[email protected] tests]$ 

雖然,畢竟我會建議使用C++功能,如vectorrandoms

+2

我想你應該在你的例子中使用'std :: vector',特別是因爲你自己推薦它。 – rodrigo

+0

我只是想根據需要用很少的更改來更正OP代碼。如果我製作了正確的c代碼,它會更接近。要做適當的C++,我需要重寫幾乎整個程序,我覺得這超出了問題的範圍。我目前不覺得足夠冒險。 – luk32