Home > Back-end >  The sprintf why no problem?
The sprintf why no problem?

Time:09-28

Char STR [16].
Sprintf (STR, "% s % s % s % s", "ABCD", "EFGH", "IJKL", "MNOP");
Printf (" STR=% s ", STR);
Why the print result is STR=ABCDEFGHIJKLMNOP

Sprintf will automatically at the end. \ 0, 4 string already accounted for 16 bytes, I understand that if the actual sprintf for writing the STR memory cache length without considering purpose, do real memory has overflow, wrote 17 byte, 17 byte automatically fill in the overflow \ 0, only the current just 17 byte nobody use, if you have any other operations of 17 byte behind it will lead to unpredictable printf

CodePudding user response:

You have a problem understanding of unpredictable
Unpredictable is unable to determine if you have any questions
not guarantee there will be a problem

CodePudding user response:

Why do you want to have a problem (O_O)?

CodePudding user response:

An array is undefined behavior, thus likely to be successful, can fail,

Suggest using snprintf

CodePudding user response:


VS2015 debugging, added a '\ 0' is crossing the line, eventually to the output, but the program to output after an error again,

CodePudding user response:

Sprintf affected 17 bytes, but for the next line of printf don't have any effect, because the printf function for the operation of the memory is read, but because of your sprintf cross-border access, 1, as you say, 17 years bytes used by other variables, will lead to uncertainty values of other variables, 2, if the byte is a system used by 17, protection function of the operating system may suspend the program run, also may make the system collapse, directly in win98 tested similar is the case, when the word, cross just crashed and 3, if the transition carefully constructed, using the loopholes of the operating system access to the target machine shell, let the other execute a program,
  • Related