When i compile my code for 100000 input array it doesn't give any error. However, when I increase input to 500000 it gives error about stack overflow. I need to increase stack size. How can I do it?
-
4Don't; use `std::vector`. – molbdnilo Oct 18 '16 at 12:23
-
Use dynamic allocation or std::vector – KIIV Oct 18 '16 at 12:23
-
@KIIV: Dynamic allocation or std::vector will allocate memory in heap not in stack – Abhineet Oct 18 '16 at 12:24
-
1Possible duplicate of [Change stack size for a C++ application in Linux during compilation with GNU compiler](http://stackoverflow.com/questions/2275550/change-stack-size-for-a-c-application-in-linux-during-compilation-with-gnu-com) – vz0 Oct 18 '16 at 12:26
-
1@Abhineet that was a whole point of the comment. I understand, if he needs bigger stack for some kind of recursion, but for static array? – KIIV Oct 18 '16 at 12:28
-
@vz0: That's specific to one compiler (but the lack of portable answers there is a reasonable hint) – MSalters Oct 18 '16 at 13:05
-
It's a compiler crash? What's the exact error? Which is your compiler? What's your platform (Windows, Linux, Android...)? – Antonio Oct 18 '16 at 13:18
2 Answers
Don't rely on large arrays with automatic storage duration. The C++ standard does not mandate a limit on the size of such arrays, but most implementations have a surprisingly small limit compared to the amount of memory that you can allocate with alternative approaches.
In your case, a std::vector<T>
where T
is the element type, would be appropriate.

- 231,907
- 34
- 361
- 483
-
1This answer http://stackoverflow.com/a/26907700/4717805 proposes another solution that I feel might be worthy looking at, since the OP seems to know the size of its arrays – cmourglia Oct 18 '16 at 12:43
The answer to the question is to check your compiler's documentation. There's often an option for setting maximum stack size. The default is usually quite small, because well-structured programs have a tree-like call structure, and so the stack take grows logarithmically with program size and complexity. You don't need much stack for a normal program.
As others have said, however, the real answer is probably to move the data off the stack and onto the heap.

- 6,258
- 1
- 17
- 18