As a C++ programmer I sometimes need deal with memory buffers using techniques from C. For example:
char buffer[512];
sprintf(buffer, "Hello %s!", userName.c_str());
Or in Windows:
TCHAR buffer[MAX_PATH+1]; // edit: +1 added
::GetCurrentDirectory(sizeof(buffer)/sizeof(TCHAR), &buffer[0]);
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:
- Is passing the buffer as
&buffer[0]better programming style than passingbuffer? (I prefer&buffer[0].) - Is there a maximum size that is considered safe for stack allocated buffers?
- Update: I mean, for example, the highest value that can be considered safe for cross-platform desktop applications on Mac, Windows, Linux desktops (not mobile!).
- Is a static buffer (
static char buffer[N];) faster? Are there any other arguments for or against it? - When using static buffers you can use return type
const char *. 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.) - What about using
static char * buffer = new char[N];, never deleting the buffer and reusing it on each call. - 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?
- Should you prefer the
sprintf_s,memcpy_s, … variants? (Visual Studio has been trying to convince me of this for a long time, but I want a second opinion :p )
I assume your interest comes about primarily from a performance perspective, since solutions like vector, string, wstring, etc. will generally work even for interacting with C APIs. I recommend learning how to use those and how to use them efficiently. If you really need it, you can even write your own memory allocator to make them super fast. If you are sure they’re not what you need, there’s still no excuse for you to not write a simple wrapper to handle these string buffers with RAII for the dynamic cases.
With that out of the way:
No. I would consider this style to be slightly less useful (admittedly being subjective here) as you cannot use it to pass a null buffer and therefore would have to make exceptions to your style to pass pointers to arrays that can be null. It is required if you pass in data from std::vector to a C API expecting a pointer, however.
This depends on your platform and compiler settings. Simple rule of thumb: if you’re in doubt about whether your code will overflow the stack, write it in a way which can’t.
Yes, there is a big argument against it, and that is that it makes your function no longer re-entrant. If your application becomes multithreaded, these functions will not be thread safe. Even in a single-threaded application, sharing the same buffer when these functions are recursively called can lead to problems.
We still have the same problems with re-entrancy.
Stack unwinding destroys objects on the stack. This is especially important for exception-safety. Thus even if you allocate memory on the heap within a function, it should generally be managed by an object on the stack (ex: smart pointer). ///@see RAII.
MS was right about these functions being safer alternatives since they don’t have buffer overflow problems, but if you write such code just as is (without writing variants for other platforms), your code will be married to Microsoft since it will be non-portable.
I’d say in almost every case, you want to use const char* for return types for a function returning a pointer to a character buffer. For a function to return a mutable char* is generally confusing and problematic. Either it’s returning an address to global/static data which it shouldn’t be using in the first place (see re-entrancy above), local data of a class (if it’s a method) in which case returning it ruins the class’s ability to maintain invariants by allowing clients to tamper with it however they like (ex: stored string must always be valid), or returning memory that was specified by a pointer passed in to the function (the only case where one might reasonably argue that mutable char* should be returned).