9

Assuming a need of a buffer with fixed size, is there a size limit or threshold, such that under that size limit it's OK to use a fast stack-allocated std::array, and above that limit it's better to use a std::vector with memory allocated dynamically from the heap (since stack memory is precious and shouldn't be consumed much)?

// 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;
trincot
  • 317,000
  • 35
  • 244
  • 286
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
  • There were already similar questions: http://stackoverflow.com/questions/1825964/c-c-maximum-stack-size-of-program and http://stackoverflow.com/questions/1825964/c-c-maximum-stack-size-of-program – László Papp Apr 05 '14 at 15:19
  • 3
    If your system provides you with 8 MiB of stack (default on Mac OS X; Linux will be similar), then you should probably start worrying at somewhere around the 1 MiB size. With a smaller stack size, worry sooner. – Jonathan Leffler Apr 05 '14 at 15:19
  • That's weird.. I always see stack allocations of `char[256]`, `char[512]`, `char[1024]` and sometimes `char[2048]` or `char[4096]` on MSDN.. `4096` is actually fairly common on MSDN's socket and pipe tutorials/docs. It's always something like: `#define BUFSIZE 4096`: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx – Brandon Apr 05 '14 at 15:26
  • 1
    Depends on how much stack other functions in the call stack might have already / will consume at the same time, especially recursive functions. Better err on the conservative side, it's less painful. – Deduplicator Apr 05 '14 at 15:26
  • I managed to link the same question twice, but I wished to have this for the second: http://stackoverflow.com/questions/216259/is-there-a-max-array-length-limit-in-c – László Papp Apr 05 '14 at 15:29
  • 1
    Indeed, 4096 is pretty common, so 1 MiB looks quite unreasonable. – László Papp Apr 05 '14 at 15:30
  • It is *implementation specific* – Basile Starynkevitch Nov 10 '14 at 19:37

1 Answers1

4

There is no official limit. You could grow or reduce the default stack size on every system.

The default warning on stack size is 16 Kb for Visual Studio user mode application and 1 Kb in kernel mode. Some static analyser tools use the same limit for warning.

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

It's only a warning, but it could be considered as a recommended stack allocation limit.

ColdCat
  • 1,192
  • 17
  • 29