Requirement
Enter the password string and compare it with the set password "1234567". If the two match, output "congratulations !", If it does not match, "try again!" Is output !".
Program bug
During actual operation, you can enter some 8-bit strings, such as 33333333, and you will also get "congratulations !", This is inconsistent with the expected features.
Causes of bugs
When redundant statements (see code comments) occur during programming, the input str length is greater than buf, leading to stack overflow. Ret is defined as the first byte occupied by ret when data is stored in the memory before the buf.
When the input string str is compared with the PASSWORD, str> PASSWORD, the ret value is 1, the memory is displayed as 10 00 00 00, and the first byte becomes 00 after being stepped on, if the memory is displayed as 00 00 00, the ret value is 0, and "congratulations!" Is output! ";
When the input string str is compared with the PASSWORD, str <PASSWORD, the ret value is-1, the memory is displayed as FF, and the first byte becomes 00 after being stepped on, if the memory is displayed as 00 FF, the ret value is not equal to 0, and the output "try again! ".
What is stack overflow?
Stack Overflow is a type of buffer overflow. Buffer overflow often leads to unpredictable consequences when useful storage units are rewritten. During the running process of the program, some memory space is usually allocated to the temporary data access needs, which is usually called a buffer zone. If the data written to the buffer exceeds its own length, the buffer cannot be accommodated, it will cause the storage units outside the buffer to be rewritten. This phenomenon is called Buffer Overflow.
Solution
Remove the redundant statements in the code, and exchange the definition sequence of ret and buf to prevent ret from being trampled on.
---------------------------- Lili split line ---------------------------- codejun is coming out --------------------
1 # include <stdio. h> 2 # include <string. h> 3 4 # define PASSWORD "1234567" 5 6 void cmp (char * str); 7 8 int main () 9 {10 char buf [1024]; 11 12 printf ("please input password: \ n"); 13 scanf ("% s", buf); 14 cmp (buf); 15 16 return 0; 17} 18 19 void cmp (char * str) 20 {21 int ret; // ret defines that when data is stored in the memory before the buf, ret 22 char buf [8]; 23 24 ret = strcmp (str, PASSWORD); 25 strcpy (buf, str); // redundant statement, the input str is longer than the buf, resulting in stack overflow 26 27 I F (ret = 0) 28 printf ("congratulations! \ N "); 29 else30 printf (" try again! \ N "); 31}