Is the difference between sprintf_s and sprintf only the buffer size safe?
NO!
Int sprintf_s (
Char * buffer,
Size_t sizeOfBuffer,
Const char * format [,
Argument]...
);
Int sprintf (
Char * buffer,
Const char * format [,
Argument]...
);
Microsoft's technical documents describe their differences as follows:
One main difference between sprintf_s and sprintf is that sprintf_s checks the format string for valid formatting characters, whereas sprintf only checks if the format string or buffer are NULL pointers. if either check fails, the invalid parameter handler is invoked, as described in Parameter Validation. if execution is allowed to continue, the function returns-1 and sets errno to EINVAL.
The other main difference between sprintf_s and sprintf is that sprintf_s takes a length parameter specifying the size of the output buffer in characters. if the buffer is too small for the text being printed then the buffer is set to an empty string and the invalid parameter handler is invoked. unlike snprintf, sprintf_s guarantees that the buffer will be null-terminated (unless the buffer size is zero ).
The main difference between sprintf_s and sprintf is that sprintf_s checks the validity of formatted characters in the formatted string, while sprintf only checks whether the formatted string or buffer is a null pointer. If an error exists, the corresponding error code is returned.
Sprintf_s also carries the buffer size for receiving formatted strings. If the formatted string is too large, sprintf_s returns an empty string and the invalid parameter handle is activated. Unlike snprintf, sprintf_s does not guarantee that the buffer end with null unless the buffer size is 0.
Is there no other difference?
The answer is no. sprintf_s stores the formatted string in the Buffer zone, fills the Buffer space not occupied by the formatted string (the Buffer after Null) in the next position into-3, sprintf does not fill in but keeps the data in the unoccupied storage location in the buffer zone.
The following code:
[Cpp]
Char State1 [50] = "ABCDE ";
Char State2 [50] = "ABCDE ";
String strTest ("Flag ");
Sprintf_s (State1, sizeof (State1), "% s", strTest. c_str ());
Sprintf (State2, "% s", strTest. c_str ());
Char State1 [50] = "ABCDE ";
Char State2 [50] = "ABCDE ";
String strTest ("Flag ");
Sprintf_s (State1, sizeof (State1), "% s", strTest. c_str ());
Sprintf (State2, "% s", strTest. c_str (); the execution result is as follows: