Correct use of sprintf and snprintf.
Consider the following flawed examples:
Void F (const char * P)
{
Char Buf [11] = {0 };
Sprintf (BUF, "% 10 s", P); // very dangerous
Printf ("% Sn", Buf );
}
Do not make the format mark "% 10s" mislead you. If the length of P is greater than 10 characters, the sprintf () write operation will cross the boundary of the Buf, resulting in a buffer overflow.
It is not easy to detect such defects because they only occur when the length of P is greater than 10 characters. Hackers usually exploit this type of vulnerabilityCodeTo intrude into seemingly safe systems.
To fix this defect, use the snprintf () function instead of sprintf ().
Function prototype: int snprintf (char * DEST, size_t N, const char * FMT ,...);
Function Description: a maximum of N-1 characters can be copied from the source string to the target string, followed by 0. Therefore, if the target string is N, it will not overflow.
Function return value: If successful, the number of characters stored in the array is returned. If an Encoding Error occurs, a negative value is returned.
Recommended usage:
Void F (const char * P)
{
Char Buf [11] = {0 };
Snprintf (BUF, sizeof (BUF), "% 10 s", P); // Note: sizeof (STR) should be used for the 2nd parameters, rather than hard-coded 11, sizeof (STR)-1 or 10
Printf ("% Sn", Buf );
}