Differences between snprintf Linux and Windows

Source: Internet
Author: User

 

One portProgramDuring the test phase, we found that some characters were lost in Linux,

Find the cause and find that _ snprintf in Windows is different from snprintf in Linux.

 

 

In Linux, sprintf automatically adds '/0' to the end, and the copy length also includes'/0 ';

 

Snprintf man has the following explanations:

 

The functions snprintf () and vsnprintf () do not write more than size bytes (including
Trailing '/0 ').

 

However, in windows, _ snprintf does not follow this rule, that is, simply copy specifies the length of characters, without automatically adding 0, and the length does not contain 0.

 

TestCodeAs follows:

 

 

# Include <stdio. h>

# Include <string. h>

 

Int main ()
{
Char Buf [20];
Char * pstr = "this is a test string ";

Memset (BUF, 0, sizeof (BUF ));

_ Snprintf (BUF, sizeof (BUF)-1, "% s", pstr );

Printf ("Buf = % s, strlen (BUF) = % d/N", Buf, strlen (BUF ));

Return 0;

}

 

In Windows, the result is:

Buf = This is a test stri, strlen (BUF) = 19

 

 

In Linux, the result is: (_ snprintf is replaced with snprintf)

Buf = This is a test STR, strlen (BUF) = 18

 

 

The subtle differences in functions between platforms will inevitably lead to problems ....

 

 

 

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.