【问题标题】:Suggested max size for stack allocations建议的堆栈分配最大大小
【发布时间】:2014-05-17 22:35:17
【问题描述】:

假设需要一个 固定大小 的缓冲区,是否有大小限制或阈值,这样在该大小限制下,可以使用快速堆栈分配的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;

【问题讨论】:

  • 如果您的系统为您提供 8 MiB 的堆栈(Mac OS X 上的默认值;Linux 将类似),那么您可能应该开始担心大约 1 MiB 大小。使用更小的堆栈大小,可以更快地担心。
  • 这很奇怪.. 我总是在 MSDN 上看到 char[256]char[512]char[1024] 和有时 char[2048]char[4096] 的堆栈分配。4096 实际上在MSDN 的套接字和管道教程/文档。总是这样:#define BUFSIZE 4096:msdn.microsoft.com/en-us/library/windows/desktop/…
  • 取决于调用堆栈中的其他函数可能已经/将同时消耗多少堆栈,尤其是递归函数。保守的一方最好犯错,这样痛苦会更小。
  • 确实,4096 很常见,所以 1 MiB 看起来很不合理。

标签: c++ c++11 memory heap-memory stack-memory


【解决方案1】:

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

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

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

http://msdn.microsoft.com/en-us/library/7yhee2f0.aspx

这只是一个警告,但可以将其视为建议的堆栈分配限制。

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2011-06-29
    相关资源
    最近更新 更多