I have always heard that strings such as "%d:%d:%f" (random example) can cause a buffer overflow, but I never really understood why.
Is it when they are used with scanf input, printf, or both? Why does it happen? I have been told this many times but couldn't find examples online.
CodePudding user response:
%d
,%d
and %f
can hardly result in a buffer overflow if used correctly with correct implementations of scanf
and printf
.
But with the %s
specifier you can get very easily a buffer overflow:
char string[10];
scanf("%s", string);
If the user types more than 9 characters, the string
array will overflow.
Also with sprintf
you can easily get a buffer overflow with any format specifier:
char string[4];
sprintf(string, "%d", 1234);
Here: the string
array needs to have 5 characters instead of 4.