I maintain a fairly large piece of legacy code that still uses strncpy
a lot. I have now started the process of replacing the usage of strncpy
with its safe counterpart strncpy_s
. I noticed that strncpy_s
is padding the destination buffer with -2 values - but only in debug builds! In release builds no padding occurs.
For instance:
char buffer[3];
// buffer becomes 00000000 00000000 00000000
memset(buffer, 0, sizeof(buffer));
// buffer becomes 01100001 00000000 11111110
// 97 ('a') 0 -2
strncpy_s(buffer, sizeof(buffer), "a", _TRUNCATE);
// i is -2
int i = buffer[2];
The MSDN docs do not mention this padding behaviour, and in my case it's really something I don't want because my legacy code relies on the fact that the zeroed parts of the buffer remain zeroed and are not overwritten during string copying.
Is there a way how I can prevent strncpy_s
from padding the destination string in debug builds?
Note that I have tested this with both Visual Studio 2010 and Visual Studio 2013.