2

I am trying to write a program that generate 5 million different random numbers in C++. 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.

user2872777
  • 99
  • 2
  • 11

2 Answers2

4
long numbers[5000000];

will try to allocate 5 million * sizeof(long) bytes of stack. 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;
simonc
  • 41,632
  • 12
  • 85
  • 103
2

You're allocating 20 MiB of data on the stack, but your system isn't configured to allow that.

  1. You don't need to save any of them if you're just printing them.
  2. You can make the variable static.
  3. You can dynamically allocate the array.

Any of those should work.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278