且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

分段故障11在Mac上的C ++

更新时间:2022-03-28 00:20:20

您已经超过了操作系统给出的堆栈空间。如果你需要更多的内存,最简单的方法是动态分配:

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 int[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<int[]> res (new int[N]);



语法,由于重载的 operator [] ,但是要获得内存操作的原始指针,你需要 res.data ()向量 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 raw pointer for memory operations you'd need res.data() with vector or res.get() with unique_ptr.