sprintf of error summarization in C + + _c language

Source: Internet
Author: User
sprintf is a variable parameter function that often goes wrong when used, and as long as the problem is usually a memory access error that can cause the program to crash.
The following is a simple summary of the error problems that sprintf frequently make:

1, buffer overflow:The length of the first argument is too short to solve: extend the length of the first argument. When printing a string, try to specify the maximum number of characters using the form "%.NS"
Char buf[5];
sprintf (BUF, ":%d", 3246);
printf ("Buf is%s\n", buf);

Modify BUF to Char Buf[6]

2, forget the first parameter: reason with printf used to use the habit, occasionally forget
Char buf[6];
sprintf (":%d", 3246);
printf ("Buf is%s\n", buf);

Error C2664: ' sprintf ': cannot convert parameter 2 from ' int ' to ' const char * '

3, variable parameters corresponding to the problem:Usually forget to provide a corresponding format of the variable parameter, resulting in all the wrong parameters, check and check it. Especially those parameters that correspond to the "*", are they provided?
Do not match an integer to a "%s"

Char buf[100];
int a=6;
sprintf (buf, ":%d,%s", 3246,a);
printf ("Buf is%s\n", buf);

Warm tip: A corresponds to%d instead of%s

4, there are the following such a mistake, I can only sense do not know how to describe. Now give an example of the wrong code and the correct code. Let's see for yourselves.
The wrong code
Char buf[15];
Char a1[] = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G '};
Char a2[] = {' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N '};
sprintf (buf, "%s%s", a1, A2); Garbled, the result is not what we need
printf ("Buf is%s\n", buf);

the right code
Char buf[15];
Char a1[] = {' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G '};
Char a2[] = {' H ', ' I ', ' J ', ' K ', ' L ', ' M ', ' N '};
sprintf (buf, "%.7s%.7s", a1, A2);//produce: "ABCDEFGHIJKLMN"
printf ("Buf is%s\n", buf);

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.