Game Development Community

Becareful using strncpy_s

by Kirby Zhang · in Torque Game Engine · 09/18/2006 (8:52 pm) · 1 replies

Not so much a bug report as a heads up on how to NOT spend a whole day tracking this down, as I just did :0

If you use Visual Studio 2005, the compiler will warn you about deprecated functions such as strncpy. I figured it was a good idea to replace them with the recommended versions. So I changed this line in BitStream::writeString
strncpy(mStringBuffer + j, string + j, maxLen - j);
to
strncpy_s(mStringBuffer + j, 256, string + j, maxLen - j);
mStringBuffer is allocated with 256 bytes, maxLen is 255, j is the first position in string which does not match mStringBuffer.

It turns out that Microsoft's strncpy_s will overflow the destination buffer if string+j happens to be the null character, given the parameter values above (MSDN doc suggests NOTHING should have been written).

The follow line will fix it:
strncpy_s(mStringBuffer + j, 256-j, string + j, maxLen - j);
where 256-j is the correct allocated size of mStringBuffer+j. I missed this and spent the whole day tracking it down. But at least I learned a lot about TNL!