Note that there are some explanatory texts on larger screens.

plurals
  1. PODealing with char buffers
    primarykey
    data
    text
    <p>As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example:</p> <pre><code>char buffer[512]; sprintf(buffer, "Hello %s!", userName.c_str()); </code></pre> <p>Or in Windows:</p> <pre><code>TCHAR buffer[MAX_PATH+1]; // edit: +1 added ::GetCurrentDirectory(sizeof(buffer)/sizeof(TCHAR), &amp;buffer[0]); </code></pre> <p>The above sample is how I usually create local buffers (a local stack-allocated char array). However, there are many possible variations and so I'm very interested in your answers to the following questions:</p> <ul> <li>Is passing the buffer as <code>&amp;buffer[0]</code> better programming style than passing <code>buffer</code>? (I prefer <code>&amp;buffer[0]</code>.)</li> <li>Is there a maximum size that is considered safe for stack allocated buffers? <ul> <li><i>Update:</i> I mean, for example, the highest value that can be considered safe for cross-platform desktop applications on Mac, Windows, Linux desktops (not mobile!).</li> </ul></li> <li>Is a static buffer (<code>static char buffer[N];</code>) faster? Are there any other arguments for or against it?</li> <li>When using static buffers you can use return type <code>const char *</code>. Is this (generally) a good or a bad idea? (I do realize that the caller will need to make his own copy to avoid that the next call would change the previous return value.)</li> <li>What about using <code>static char * buffer = new char[N];</code> , never deleting the buffer and reusing it on each call.</li> <li>I understand that heap allocation should be used when (1) dealing with large buffers or (2) maximum buffer size is unknown at compile time. Are there any other factors that play in the stack/heap allocation decision?</li> <li>Should you prefer the <code>sprintf_s</code>, <code>memcpy_s</code>, ... variants? (Visual Studio has been trying to convince me of this for a long time, but I want a second opinion :p )</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload