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_s
1) buffer
and &buffer[0]
should be equivalent.
2) Stack size limits will depend on your platform. For most simple functions, my personal rule of thumb is anything over ~256KB is declared dynamically; there's no real rhyme or reason to that number, though, it's just my own convention and it's currently within the default stack sizes for all of the platforms I develop for.
3) Static buffers aren't faster or slower (for all intents and purposes). The only difference is the access control mechanism. The compiler generally places static data in a separate section of the binary file than non-static data, but there is no noticeable/significant performance benefit or penalty involved. The only real way to tell for sure is to write the program both ways and time them (since many of the speed aspects involved here are dependent on your platform/compiler).
4) Don't return a const
pointer if the caller will need to modify it (that defeats the point of const
). Use const
for function parameters and return types if and only if they are not designed to be modified. If the caller will need to modify the value, your best bet is for the caller to pass the function a pointer to a pre-allocated buffer (along with the buffer size) and for the function to write the data into that buffer.
5) Reusing a buffer may lead to a performance improvement for larger buffers due to bypassing the overhead that is involved in calling malloc
/free
or new
/delete
each time. However, you run the risk of accidentally using old data if you forget to clear the buffer each time or you try to run two copies of the function in parallel. Again, the only real way to know for sure is to try both ways and measure how long the code takes to run.
6) Another factor in stack/heap allocation is scoping. A stack variable goes out of scope when the function it lives in returns, but a variable that was dynamically allocated on the heap can be returned to the caller safely or accessed the next time the function is called (a la strtok).
7) I would recommend against the use of sprintf_s
, memcpy_s
, and friends. They are not part of the standard library and are not portable. The more you use these functions, the more extra work you will have when you want to run your code on a different platform or use a different compiler.