Snprintf () function return value "trap"

Source: Internet
Author: User

 

I recently optimized a Linux-C Applet and used the snprintf () function to write data to an array (or string. I don't need sprintf () because it is not safe enough. Accidentally, it will cause memory overflow, resulting in "segment errors "! I have known and used snprintf () for a long time, but today I fully understand the meaning of its return value. Function prototype:
Int snprintf (char * STR, size_t size, const char * format ,...);Size is used to limit the number of bytes (including '\ 0' at the end) written to Str '). Because if the sprintf () function is successful, the number of bytes (number of characters) written to the sprintf () function is returned, and I always thought that the snprintf () function is also like this, that is, snprintf () the function does not return an integer greater than the size. See the following manual: The functions snprintf () and vsnprintf () do not write more than size bytes (including the trailing '\ 0 '). if the output was truncated due to this limit then the return value is the number of characters (not including the trailing '\ 0') which wowould
Have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated.
If the output is truncated due to the size limit, the returned value is "if there is enough storage space YingNumber of characters that can be output (excluding '\ 0' at the end of the string) ". The value is equal to or greater than the size! That is to say, if the string that can be written is "0123456789 abcdef" with a total of 16 bits, but the size limit is 10, then the returned value of snprintf () will be 16
Instead of 10! The above content also says that if the returned value is equal to or greater than the size, it indicates that the output string is truncated (truncated ). Ladies and Gentlemen ~ Note ~     Address: http://snailwarrior.blog.51cto.com/680306/152913

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.