Pitfalls of strcat Functions

Source: Internet
Author: User

Pitfalls of strcat Functions
Let's take a look at the following code:

1 # include <iostream> 2 # include <stdlib. h> 3 using namespace std; 4 5 int main () 6 {7 char * p1 = "123"; 8 char * p2 = "ABC "; 9 char str [50] = "xyz"; 10 strcat (p1, p2); 11 strcpy (str + 2, p1); 12 cout <str <endl; 13 system ("pause"); 14 return 0; 15}

 

At first glance, the original intention of this Code is to link p2 to the back of p1, p1 is 123ABC, and then move the str character array backward to two positions, copy p1 to the memory after this position. The result is xy123ABC. However, we run this code and find that the program has crashed. We call the stack and find that the function is located in this line of code. How is this going? Check the usage of the strcat function, it is found that when the strings p1 and p2 are connected, the connected strings are stored in p1 together, which means that the size of P1 must accommodate the connected strings. But essentially the string "123" is saved in the constant area of the program, the constant zone can only run read without writing, so we define a large array in the stack area to save the connected results. Char p1 [20] = "123"; now let's run it again and see the result: This is correct.

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.