title: leave it on stack or put in on heap?
body: <p>It happens that function uses local buffer to prepare some block of data of limited size and pass it to the other function, just like this:</p>
  
  <pre><code>void foo()
  {
    char buffer[MAX_SIZE];
    size_t size = write_fancy_things(buffer);
    bar(buffer, size);
  }
  </code></pre>
  
  <p>However, depending on value of <code>MAX_SIZE</code>, you might be worried about eating too much stack and replace the code with something similar to the following example (but hopefully with more care about memory management):</p>
  
  <pre><code>void foo()
  {
    static char *buffer = new char[MAX_SIZE]; 
    size_t size = write_fancy_things(buffer);
    bar(buffer, size);
  }
  </code></pre>
  
  <p>In general case, these two functions should behave the same. However, in the first example, if <code>MAX_SIZE</code> is too large, we're more likely to hit stack limit. Using large values might be fine if you're aware where the function is used, but sometimes you're not. </p>
  
  <p>In the second example we're dealing with additional indirection and buffer is more prone to CPU cache miss, which may be a case if <code>foo</code> lies on a low latency critical path and we expect the cost of preparing the buffer to be very low in most cases.</p>
  
  <p>What size would you consider as being too large to put on stack? Also is there any penalty on putting big block of data on the stack, but using only small portion of it?</p>
  
  <p><strong>EDIT:</strong> The <code>write_fancy _things</code> is just a synonym for saying *I'm writing some data to the buffer, between 1 and MAX_SIZE bytes*. You can think about the second <code>foo</code> example as a class method, and the static pointer as a class member allocated in constructor. I've just probably oversimplified things, but didn't want to introduce more complexity than needed and focus on the stack concerns.</p>