Mac 上 C++ 中的分段错误 11

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19522192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:55:44  来源:igfitidea点击:

segmentation fault 11 in C++ on Mac

c++segmentation-fault

提问by mariusz2108

When I try to run this

当我尝试运行它时

int N=10000000;
short res[N];

I get segmentation fault 11

我得到分段错误 11

when I change to

当我改为

int N=1000000;
short res[N];

it works fine

它工作正常

回答by Bartek Banachewicz

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::vectoris preferred in this context, because the above requires you to freethe memory by hand.

但是,std::vector在这种情况下是首选,因为上面需要您free手动进行记忆。

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_ptrarray specialization, too:

如果你可以使用 C++11,你也可以通过使用unique_ptr数组特化来节省一些时间:

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 vectoror res.get()with unique_ptr.

上述两种自动方法仍然可以使用熟悉的使用res[index]语法由于超载operator[],但要得到你需要的内存操作的原始指针res.data()vectorres.get()unique_ptr

回答by IdeaHat

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

您不能在堆栈上分配所有这些。尝试short* res = new short[10000000];并且不要忘记清理。

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

或者,您可以使用std::vector<short> res(10000000);