I was looking at the following example in a book, and it seems to me that it will cause stack smashing:
int read_line(char str[], int n)
{
int ch, i = 0;
while ((ch = getchar()) != '\n')
if (i < n)
str[i++] = ch;
str[i] = '\0';
return i;
}
If I pass it an array with room for 10 chars, and n = 10, the if-statement will be true up to and including 9, and i will be incremented to 10.
Then, it will write the '\0' character at str[10] which would be just past the end of the array?
It works just fine, though (tried building with gcc on Linux, clang on Mac and VS on Windows). VS on Windows is the only one showing an error when running the program, even though I have tried setting -fstack-protector in e.g. clang.