I have written the following code:
#include <stdio.h>
int main() {
char s[10];
while (fscanf(stdin, "s", s) != 1) {
}
printf("%s", s);
}
However the code runs perfectly fine.
How is this?
The buffer s
is size 10 but if i input a string such as helloworld
which is 10 characters long the printf
statement will print helloworld
. How is this possible? I thought that it would print helloworl
which i thought would look like this:
index 0: h
index 1: e
index 2: l
index 3: l
index 4: o
index 5: w
index 6: o
index 7: r
index 8: l
index 9: \0
why does this still work for me? and print helloworld
? it seems like the null terminator is not even there. what is going on?
CodePudding user response:
On this line: char s[10];
You asked for, and were allocated, 10 bytes in the array s
.
All other data is beyond your control, and could have any value at all.
It could be used by device-drivers, or other programs, or even not be valid memory at all.
Then using fscanf
you filled in 11 bytes with values HelloWorld
and a \0
Terminator.
This is where the trouble starts. Your code filled in byte #11, which you have not explicitly reserved for your use.
printf
will print a string until it finds a \0
terminator.
You do not have a guarantee of a terminator, so anything could happen.
Lucky for you, it seems that extra byte is available, and has not been overwritten by any other task/process/thread/device. There happens to be a \0
at the end of the text, and it behaves normally. But that is undefined behavior, and anything could very well have happened.
It would be totally legit if your computer had printed:
HelloWorldPrepareForGozerTheGozerian
CodePudding user response:
Only you know the size of s
buffer.
s
is just a pointer for fscanf function. It doesn't matter how big is your buffer
index 0: h
index 1: e
index 2: l
index 3: l
index 4: o
index 5: w
index 6: o
index 7: r
index 8: l
index 9: d
index 10: \0
This is in the thread stack. It needs 11 elements, but it is not a problem for the compiler. Only you can care about it