0

I want to generate 100 million integer numbers but the code below can just generate 100 thousand numbers if I go above this number I get a stop working error.

#include <iostream>
#include <random>
#include <time.h>
using namespace std;
int main()
{
    const int n = 100000;
    int numbers[n] = {0};

    srand(time(NULL));
    for (size_t i = 0; i < n; i++)
        numbers[i] = rand() % 100;

    return 0;
}
meaning-matters
  • 21,929
  • 10
  • 82
  • 142
Milad ABC
  • 337
  • 1
  • 2
  • 13
  • 8
    Stack space is limited (usually to ~1MB or so). Use `std::vector` instead. – nwp Mar 04 '18 at 18:50
  • What do you need 100 million random numbers `< 100` in an array for? – meaning-matters Mar 04 '18 at 18:54
  • Try `std::unique_ptr numbers = std::make_unique(n);` instead of `int numbers[n] = {0};` – Killzone Kid Mar 04 '18 at 18:59
  • @meaning-matters I want to test sorting algorithms with large numbers. – Milad ABC Mar 04 '18 at 19:02
  • @nwp: Answers go in the answer section. Thanks. – Lightness Races in Orbit Mar 04 '18 at 19:09
  • @LightnessRacesinOrbit This question has been asked thousands of times and needs to be closed, not answered. Additionally that wasn't an answer, it's a quick fix for when you can't be bothered to learn about what is going on. We seem to have very different ideas of what SO is for and what questions and answers should be like. – nwp Mar 04 '18 at 19:35
  • @nwp: You cannot close a question saying it does not belong here and then proceed to answer it in comments. That is the worst of both worlds. We do have different ideas: mine is correct, and yours is not. This is a Q&A. We have quality controls... on answers. If your comment were wrong, we would not be able to signify that with a downvote. If you're going to answer, answer in the answer section; that's why it's called the answer section. Hover over the "add a comment" link to discover what comments are for; the tooltip text actually says literally what I just said. Thanks. – Lightness Races in Orbit Mar 04 '18 at 19:42

2 Answers2

0

It's because you are using stack instead of heap memory. See this link similar to your question.

Try the following code:

const int n = 1000000;
int *numbers = new int[n];

// your code goes here

delete[] numbers;
return 0;
tmguvenc
  • 36
  • 2
0

you should declare the array globally because in main the array is allocated at stack.Default limit is 8Mb. But if you declare globally the array is stored on data segment which has allocation as much as free memory.

#include <bits/stdc++.h>
using namespace std;
const int n = 100000000;
int numbers[n] = {0};
int main()
{
    srand(time(NULL));
    for (size_t i = 0; i < n; i++)
        numbers[i] = rand() % 100;

    return 0;
}