[英]5 million random number program won't run
I am trying to write a program that generate 5 million different random numbers in C++. 我正在尝试编写一个在C ++中生成500万个不同随机数的程序。 Below is the code:
下面是代码:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
unsigned before = clock();
srand(time(NULL));
long numbers[5000000];
for (int i = 0; i < 5000000; i++)
numbers[i] = rand() % 5000000;
for (int i = 0; i < 5; i++)
cout<<numbers[i]<<endl;
cout<<clock() - before<<endl;
return 0;
}
Every time I run it, nothing happens and the program crashes on me. 每次我运行它时,什么都没有发生,并且程序崩溃了。 I can't seem to find what I'm doing wrong since the code is so simply.
我似乎找不到我在做什么错,因为代码是如此简单。 Can someone please help me?
有人可以帮帮我吗? Thank you.
谢谢。
long numbers[5000000];
will try to allocate 5 million * sizeof(long)
bytes of stack. 将尝试分配500万*
sizeof(long)
个字节的堆栈。 This will almost certainly overflow. 这几乎肯定会溢出。
You could move the variable to have static duration instead 您可以将变量移动为具有静态持续时间
static long numbers[5000000];
or you could allocate it dynamically 或者您可以动态分配它
long* numbers = new long[5000000];
// calculations as before
delete [] long;
You're allocating 20 MiB of data on the stack, but your system isn't configured to allow that. 您正在堆栈上分配20 MiB数据,但是您的系统未配置为允许这样做。
static
. static
。 Any of those should work. 这些都应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.