segmentation fault 11 in C++ on Mac(Mac 上 C++ 中的分段错误 11)
问题描述
当我尝试运行时
int N=10000000;
short res[N];
我得到分段错误 11
当我换成
int N=1000000;
short res[N];
效果很好
推荐答案
您已超出操作系统提供的堆栈空间.如果需要更多内存,最简单的方法是动态分配:
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];
但是,在这种情况下,std::vector 是首选,因为上述要求您手动释放内存.
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);
如果你可以使用 C++11,你也可以通过使用 unique_ptr 数组特化来节省一些时间:
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]);
由于重载了 operator[],上述两个自动方法仍然可以与熟悉的 res[index] 语法一起使用,但要获取内存操作的原始指针你需要 res.data() 和 vector 或 res.get() 和 unique_ptr.
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.
这篇关于Mac 上 C++ 中的分段错误 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mac 上 C++ 中的分段错误 11
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
