segmentation fault 11 in C++ on Mac

不想你离开。 提交于 2019-12-03 17:47:39

问题


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


回答1:


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.




回答2:


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);



来源:https://stackoverflow.com/questions/19522192/segmentation-fault-11-in-c-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!