Within my C++ code, within Visual Studio, I’m generating a simple string "%02d"
with an int
value of 1
. My buffer is exactly 64 characters in capacity, and I’m specifying 64 as my buffer’s length to sprintf_s
:
char string[64];
sprintf_s( string, 64, "%03d", int(1) );
I added watch entries to monitor several characters that follow the terminator:
string + 4, string + 5, string + 6
, etc. This data all starts out as either 0’s or random garbage, depending on where the string buffer is declared. But immediately after sprintf_s
is called, this area of data turns into 'þ'
characters (which appears to be the value 231).
From what I can tell, it looks like sprintf_s
is filling the remaining/unneeded part of my buffer with this character. If I intentionally set the buffer capacity to a number lower than the actual buffer size, it will only fill the contents up to that specific lower number.
Is this normal behavior? The exe I’m running this through is built in debug mode with multiple debugging options tweaked, so I guess it’s possible some component of the debugger is causing this. I can’t seem to find any documentation that mentions this. The function is respecting the buffer capacity, but it seems to be filling all of the buffer, even when it is 2K+.
2
This sounds like a perfectly reasonable thing for sprintf_s to do in debug mode. <…> If you’re concerned with performance, don’t build in debug mode. Debug mode is for creating an executable that is easier to debug, and filling a buffer with a known value makes it easier to see if you’ve read past the valid part somewhere.
–
Miles Budnek
1