-
How is this possible?
#include <stdio.h>
int main() {
char name[4];
printf("enter name: ");
scanf("%s",name);
printf("Hello %s",name);
return 0;
}
Out put:
enter name: 012345
Hello 012345
How come it doest error ?
char name[4]
should only hold 3 characters w. a null at the end.
Why is this case different?
-
Try running the program a few times in a row. this may cause the program to crash. it should not work but it writes over memory if should not have access to so better to use the right sized arrays.
-
Yes I know this,
But why did it even work.
That was my whole point.
Even if it over rights the buffer im still printing out to stdout name[4].
Not name[5] or [6]
So again, why is it printing the extra memory spaces
-
Aren't you overwriting the null?
-
You are outputting the string that starts at name[0], printf() does not know how long the string is, (that is why you use a NULL to terminate it). You have overwritten the memory locations after the last element of name[], if there is nothing there your program relies on later, you will get away with that, it may work sometimes and not others, it just depends what is there. C does nothing to protect you from yourself.
-
Well it works because the compiler doesn't know how long the string typed in is going to be. There isn't a "This char array isn't long enough to be considered practical for string storage purposes" warning.
Anyway, as we all know, C trusts the programmer so it lets you get away with things you really shouldn't be doing.