I spent a few hours grappling with data corruption until I found something interesting.
My code was getting crunched after a certain point because of an sprintf overwriting the first byte of the array right after it.
After some research, I found something interesting and irritating.
According to MSDN,
Security Note There is no way to limit the number of characters written, which means that code using sprintf is susceptible to buffer overruns. Consider using the related function _snprintf, which specifies a maximum number of characters to be written to buffer, or use _scprintf to determine how large a buffer is required. Also, ensure that format is not a user-defined string.
Oh, glee and rapture. This problem was ignored in the command line version because the same area was overwritten each time. But in this new world of GUI, it's a problem, particularly because the array (here, array2) is a time difference that increases in length, and doesn't have a problem before it passes 100 seconds.
My code approximates to this:
struct foobar
{
array1[25];
array2[16];
};
int main (void)
{
struct foobar foo;
foo.array2[0] = '0'; foo.array2[1] = '0'; foo.array2[2] = ':';
foo.array2[3] = '0'; foo.array2[4] = '0'; foo.array2[5] = ':';
sprintf(&(foo.array2[6]), "%9f", diff/(1.0e6)); //This overwrites by one byte.
//Function that writes to array 1 goes here (also using sprintfs, but with enough of a buffer that the danger is minimized, or something.)
}
If the time in array2 gets too large, it overflows the buffer and corrupts the variable that follows it.
I have managed to get this under control by placing the sprintf and its array as shown above. This way, the function writing array1 can't be overwritten by the already-completed array2 sprintf, and array2 has been placed at the end of the struct so that it won't be able to overflow into another variable.
But this is a cop out.
How can I fix this without relying on placement of code? I don't know when the time will roll over to 100 because of the data's nature. I also don't know what the maximum size will be on the time difference (from the start), so I can't use snprintf or scprintf. Of course, those don't seem to be in the libraries available to me, either...
Thanks in advance.