troflip wrote:
strncpy is a little different than what I'm talking about.
strncpy says "copy n bytes from src, into dest".
Strncpy says: "Copy src to dest, but not more than n bytes."
What I'm talking about is, copy as much as src as possible into dest, but indicate dest is only n chars long, so don't copy more than that.
An example from the windows sdk would be StringCchCopy.
e.g.
MSDN reference to StringCchCopy
Which is then the exact same. strncpy doesn't copy beyond the null terminator, doesn't overrun the target buffer but always null-terminates the dest string. The Microsoft-function StringCchCopy copies the string up to the null terminator, doesn't overrun the target buffer and null-terminates the final string. The three differences are that the Microsoft one isn't supported outside of windows, the argument order is different and the language design is slightly different (IE, the C standard things use standard C types, while the Microsoft one uses types I've never heard of).
Of course, it is impossible to avoid overflows if you have to copy all of src into a fixed length buffer. Your only choice then is to allocate a buffer as long as the src, and copy into that.
Which would equate what all modern languages can do with a clone-like facility. That includes C++, C#, java and a bunch of others. With a minuscule bit of trouble you can do the same in C.
Pop quiz: what happens when you don't have the memory to copy it?