10

When I try to run this

int N=10000000;
short res[N];

I get segmentation fault 11

when I change to

int N=1000000;
short res[N];

it works fine

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
mariusz2108
  • 851
  • 2
  • 11
  • 36
  • 15
    [Stack Overflow](http://en.wikipedia.org/wiki/Stack_overflow#Very_large_stack_variables) – Yu Hao Oct 22 '13 at 15:32
  • So, what is your issue? You are trying to allocate a buffer on the stack that is probably too large for the environment. There is a limit on stack size. If you need to create a buffer that big, it sholud be via new() on the heap. – OldProgrammer Oct 22 '13 at 15:34
  • @YuHao Don't you mean [Stack Overflow](http://stackoverflow.com)? – stefan Oct 22 '13 at 15:36
  • possible want to read [Segmentation fault on large array sizes](http://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes) or [Creating an 2-dimensional array of a struct results in crash](http://stackoverflow.com/questions/18923339/creating-an-2-dimensional-array-of-a-struct-results-in-crash) – user1810087 Oct 22 '13 at 15:37
  • possible duplicate of [Segmentation fault on large array sizes](http://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes) – stefan Oct 22 '13 at 15:37

2 Answers2

15

You've exceeded your stack space given by the OS. If you need more memory, the easiest way is to allocate it dynamically:

int N=1000000;
short* res = new short[N];

However, std::vector is preferred in this context, because the above requires you to free the memory by hand.

int N = 1000000;
std::vector<short> res (N);

If you can use C++11, you can possibly save some fraction of time by using unique_ptr array specialization, too:

std::unique_ptr<short[]> res (new short[N]);

Both of the automatic methods above can still be used with familiar res[index] syntax thanks to overloaded operator[], but to get the raw pointer for memory operations you'd need res.data() with vector or res.get() with unique_ptr.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
0

You can't allocate all that on the stack. Try short* res = new short[10000000]; and don't forget to clean up.

Alternatively, you can use std::vector<short> res(10000000);

IdeaHat
  • 7,641
  • 1
  • 22
  • 53