0

Simple problem: My code blocks of able to compile the code below and worked well:

int a[2000000];

My code blocks of able to compile the code below But my program crashed immediately after:

int a[2000000];
int b[2000000];

1) What is the reason and why? (my ram 16 GB !! and this just took 0.3MB so whats the problem?)

2) How to fix or use an alternate way? (but i need to create so much of arrays)

3) Is there way to increase memory of an array?


Related problem(i think so):

My code blocks of able to compile the code below and worked well:

unsigned long int a=100000000000;

My code blocks of able to compile the code below But my program crashed immediately after i enter the same number(100000000000):

unsigned long int a;
 cin>>a;

What to do?

mike
  • 78
  • 1
  • 9
  • 4
    Probably stack overflow. In general, forget arrays and use `std::vector` or other standard containers. – Fred Larson Dec 07 '16 at 15:35
  • i don't think that any c++ beginner would need to declare an array of size `2000000` – Yousaf Dec 07 '16 at 15:36
  • Do you really need that much of an automatic storage? If you do, you'd have to increase your stack limit. – SergeyA Dec 07 '16 at 15:37
  • 2
    My issue with the dupe closure is that it is a C question. The remedy in the accepted answer gives advice that is not best practice/recommended in C++. – NathanOliver Dec 07 '16 at 15:38
  • @NathanOliver, I do agree with you. Should we reopen and have a canonical C++ answer? – SergeyA Dec 07 '16 at 15:40
  • 1
    @NathanOliver: Good point. I failed to notice that. Would this one be better? http://stackoverflow.com/q/9016538/10077 – Fred Larson Dec 07 '16 at 15:41
  • @SergeyA I almost think the other question getting tagged as C++ and adding a C++ work around to the accepted answer would be the best thing. Not sure if Borgleader is up for that, – NathanOliver Dec 07 '16 at 15:42
  • @FredLarson I went ahead and closed it as a dupe your suggestion. Still think we might want to improve the C one to be C,C++ but that might need a meta question to get community approval. – NathanOliver Dec 07 '16 at 15:48
  • @NathanOliver: I know what you mean. That ASCII art explanation is very good and language agnostic. – Fred Larson Dec 07 '16 at 15:51
  • sorry! guys! i have added a few! – mike Dec 07 '16 at 15:54

2 Answers2

4
int a[2000000];

That overflows your stack limit. You can use a std::vector<int> a(2000000); instead, which will use dynamic storage allocation (which is unlimited theoretically).

πάντα ῥεῖ
  • 83,259
  • 13
  • 96
  • 175
1

Compiled executables have stack limits

(MSVC docs)

Without this option the stack size defaults to 1 MB.

Your code is overflowing the stack space

int a[2000000];

Stack is a precious limited resource, if you need to allocate huge chunks of memory consider doing it in the heap.

Cfr. What and where are the stack and heap?

Community
  • 1
  • 1
Marco A.
  • 41,192
  • 25
  • 117
  • 233