I have a simple function that writes some data to a new file. It works, and the file is written, but I get the above mentioned error while debugging in MSVS Express 2013.
void writeSpecToFile(const char *fname); //in header file.
char myChar [20];
sprintf(myChar, "aa%03daa%daa", i1, i2);
const char* new_char = myChar;
writeSpecToFile(myChar);
As seen, I simply insert some variables into a string using sprintf (works fine). Now whether I pass myChar or new_char, it still gives me the corruption error.
What went wrong?
Why did you declare you character buffer a size of 20? More than likely the sprintf
placed more characters than that can fit in myChar.
Instead, use
If you're going along the "guess the biggest size for my array" route, the last thing you want to do is attempt to count, right down to the last character, how big to make the buffer. If you're off by a single byte, that can cause a crash.
Assuming 32-bit int
, printing one with %d
will yield a maximum of 8 visible characters.
Your format-string also contains 6 literal a
-characters, and we should not forget the 0-terminator.
All in all: 2*8+6+1 = 23 > 20
!!
Your buffer must be at least 23 byte big, unless there are other undisclosed input-restrictions.
Personally, I would give it a round 32.
Also, better use snprintf
and optionally verify the full string did actually fit (if it does not fit you get a shortened string, so no catastrophe).
char myChar [32];
snprintf(myChar, sizeof myChar, "aa%03daa%daa", i1, i2);
Beware that the Microsoft implementation is non-conforming and does not guarantee 0-termination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With