I was reading about the vulnerabilities in strings in C and then I came across this code. Could anyone give me an explanation why this is vulnerable? Thanks in advance.
Asked
Active
Viewed 104 times
0
-
Check array indexing. – Some programmer dude May 15 '21 at 08:35
-
4`strcpy` copies `strlen + 1` characters. What happens when `strlen(str) == MAXSIZE`? – May 15 '21 at 08:36
-
2Writing beyond the bounds of an array is undefined behavior. Look at your `while` loop. Do you think that `j` will always be between `0` and `9`? And as mentioned, your `strcpy` call is unsafe. – Tom Karzes May 15 '21 at 08:37
1 Answers
1
char buf[MAXSIZE];
if (strlen(str) > MAXSIZE)
return;
strcpy(buf, str);
This code incorrectly check for maximum length. C string have a nul at the end of the string to mark the end of the string. strcpy() will copy it. To accomodate for this nul, the test must be:
if (strlen(str) >= MAXSIZE)
The code below is also incorrect. int i[10]; int j = 0;
while (j < 10000){
i[j] = 5;
++j;
}
This code will overwrite the data in memory after the 10 integers of array i. This will create an undefined behavior, probably a crash but maybe something more subtle...

fpiette
- 11,983
- 1
- 24
- 46