Boiz's C ++ Memo (3) - Note a trap of the strcpy function

xiaoxiao2021-03-06  18

In the 9CBS Forum, I saw someone asked the following question. I can't help but remember that I have encountered a class of Bug, so I feel that it is necessary to write down, so that I will forget it for a long time.

Let's take a look at the problem first:

Bowex () ///

Char uu [3] [2]; cstring s; for (int i = 0; i <3; i ) {s = "me"; strcpy (uu [i], s);}

What is the content of the array uu after running the above programs is

UU [0] ---> I am me uu [1] ---> I am uu [2] ---> I

Not uu [0] ---> My uu [1] ---> My uu [2] ---> Why? Strange! Thank you

Netizen "Qunkangli (maintenance costs and programmers's square is proportional)" gives an explanation:

"Char uu [3] [3]; // This will be, the string end value accounts for one character width."

This explanation is right, but I still have to emphasize the serious consequences that this situation may be:

Like this situation, I think of the strcpy function may cause illegal memory access, that is, if

Strcpy copy of the destination address is not enough, then STRCPY will occupy the address behind the space,

This may cause some data to be accidentally modified, resulting in crashing or data exceptions. Whose reason

This feeling is because there is a program that has encountered a program, that is, because of the content of Strcpy copy

Overnal, the data of the members of the member subsequent subsequently subsequently turned 0, and the resulting procedure of course appeared.

Assume that the above FOR cycle is used to replace the following statement, it is more absurd, because there will be garbled.

Char uu [3] [2]; cstring s;

S = "I"; STRCPY (uu [2], s); strcpy (uu [1], s); strcpy (uu [0], s);

You can compile the above code, run the program, you can see garbled in the uu array.

If the output is output, it should be like this.

UU [0] ---> My uu [1] ---> (empty string) uu [2] ---> (empty string)

What is why everyone should have a glimpse?

转载请注明原文地址:https://www.9cbs.com/read-44547.html

New Post(0)