Translation - Japanese: sprintf 使用時の変数化けについて - KBA203916 - Community Translated (JA)
When using sprintf to store a string in a character array, I notice that certain other variables get corrupted. What is the cause for this, and how can I prevent this issue?
The sprintf function places the converted string in the memory location starting from the location indicated by the pointer (which is passed when calling the sprintf function) and ending at the location "starting location + length of the string + 1". The extra 1 is added for the null character which indicates the end of the string. Therefore, if the length is greater than the size of the character array declared to store the string, there is a possibility of corruption of other variables that are present at memory locations following this character array.
For example, consider the code shown below:
This code places the result on a memory location of 12 bytes (11 bytes for the actual string characters and 1 byte for the null character, which indicates the end of the string) starting from the address of str. The compiler might have allocated the 11th and 12th bytes to some other variable(s). Therefore, variables located at the 11th and 12th bytes might get corrupted due to this sprintf call. To prevent this, you must make sure that the length of the character array is sufficiently large to accommodate the complete string and the null character.
In this example, declaring "str" with a length of 12 or greater would prevent corruption of other variables.