堆栈分配的建议最大大小



假设需要一个固定大小的缓冲区,是否有大小限制或阈值,以便在该大小限制下可以使用快速堆栈分配的std::array,并且超过该限制最好使用具有从堆动态分配内存的std::vector(因为堆栈内存很宝贵,不应该消耗太多)?

// I think allocating 32 bytes on the stack is just fine.
std::array<BYTE, 32> smallBuffer;
// For 32KB, it's better getting memory from the heap.
std::vector<BYTE> bigBuffer(32*1024);
// Is it better to allocate a 1KB buffer on the stack (with std::array)
// or is it too much, and it's better to allocate on the heap (using std::vector)?
// What about 512 bytes? And 4KB?
// Is there a suggested size threshold?
std::array<BYTE, 1024> buffer;

没有官方限制。您可以增加或减少每个系统上的默认堆栈大小。

对于 Visual Studio 用户模式应用程序,堆栈大小的默认警告为 16 Kb,在内核模式下为 1 Kb。某些静态分析工具使用相同的警告限制。

warning C6262: Function uses '30000' bytes of stack: exceeds /analyze:stacksize'16384'. Consider moving some data to heap



https://learn.microsoft.com/en-us/cpp/code-quality/c6262这只是一个警告,但可以将其视为建议的堆栈分配限制。

最新更新