C language snprintf function

Source: Internet
Author: User

Int snprintf (char * restrict Buf, size_t N, const char * restrict format ,...);

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 the value is successful, the length of the string to be written is returned. If an error occurs, a negative value is returned.

Result1 (recommended)

# Include <stdio. h>
# Include <stdlib. h>

Int main ()
{
Char STR [10] = {0 ,};
Snprintf (STR, sizeof (STR), "0123456789012345678 ");
Printf ("str = % s \ n", STR );
Return 0;
}

Root]/root/lindatest
$./Test
Str= 012345678

Result2: (not recommended)

# Include <stdio. h>
# Include <stdlib. h>

Int main ()
{
Char STR [10] = {0 ,};
Snprintf (STR, 18, "0123456789012345678 ");
Printf ("str = % s \ n", STR );
Return 0;
}

Root]/root/lindatest
$./Test
Str= 01234567890123456

Test the returned values of the snprintf function:

# Include <stdio. h>
# Include <stdlib. h>

Int main ()
{
Char str1 [10] = {0 ,};
Char str2 [10] = {0 ,};
Int ret1 = 0, ret2 = 0;
Ret1 = snprintf (str1, sizeof (str1), "% s", "ABC ");
Ret2 = snprintf (str2, 4, "% s", "aaabbbccc ");
Printf ("aaabbbccc length = % d \ n", strlen ("aaabbbccc "));
Printf ("str1 = % s, ret1 = % d \ n", str1, ret1 );
Printf ("str2 = % s, ret2 = % d \ n", str2, ret2 );
Return 0;
}

[Root]/root/lindatest
$./Test
Aaabbbccc length = 9
Str1 = ABC, ret1 = 3
Str2 = aaa, ret2 = 9

**************************************** ***********************************

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 use this type of fragile code to intrude into seemingly secure 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 );
}

**************************************** **********************************

As we all know, sprintf does not check the length of the target string, which may cause many security problems. Therefore, we recommend using snprintf.

The declaration of snprintf (_ snprintf) is as follows:

Int _ snprintf (
Char * buffer,
Size_t count,
Const char * Format [,
Argument]...
);

If Len <count, then
Len characters are stored in
Buffer, a null-Terminator is appended, And Len is returned.

If Len = count, then
Len characters are stored in
Buffer, no null-Terminator is appended, And Len is returned.

If Len> count, then
Count characters are stored in
Buffer, no null-Terminator is appended, and a negative value is returned.

The most common errors are:
1.
Char SA [256] = {0 };
_ Snprintf (SA, sizeof (SA), "% s", Sb );
// Error cause: When the SB length is greater than or equal to 256, SA will not end with '\ 0'

2.
Char SA [256];
_ Snprintf (SA, sizeof (SA)-1, "% s", Sb );
// Error cause: When the SB length is greater than or equal to 255, SA will not end with '\ 0' and will not initialize SA

3.
Char SA [256];
_ Snprintf (SA, sizeof (SA)-1, "% s", Sb );
Sa [sizeof (SA)] = 0;
// Error cause: the last row of the array is out of bounds.

Correct usage
1. // recommended usage
Char SA [256];
Sa [sizeof (SA)-1] = 0;
_ Snprintf (SA, sizeof (SA), "% s", Sb );
If (SA [sizeof (SA)-1]! = 0)
{
Printf ("Warning: string will be truncated ");
Sa [sizeof (SA)-1] = 0;
}

2.
Char SA [256] = {0 };
Int result = _ snprintf (SA, sizeof (SA), "% s", Sb );
If (result = sizeof (SA) | result <0)
{
Printf ("Warning: sting will be truncated ");
Sa [sizeof (SA)-1] = 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.