I expanded your code into a complete program as follows:
#include "stdio.h"
main () {
char fmt[2] = "% ";
int value = 23;
do {
printf("Enter a format specifier: ");
scanf(" %c", fmt+1);
printf(fmt,value);
} while(*(fmt+1) != 'q');
}
... and got the following result:
Enter a format specifier: i
23h (Enter a format specifier: d
23h (Enter a format specifier: x
17h (Enter a format specifier: o
27h (Enter a format specifier: q
qh (
This output was a little different from what you seem to have observed, but I think it might be the same in principle. If so, I think it is as you suspected: a buffer overflow error caused by the fact that fmt
is declared as a char array that isn't long enough to include the null that should be at the end of any C string. Thus, printf()
kept on writing random data after the format character until it happened to come across a null.
Changing the fourth line of code to ensure that the string has enough space for the visible characters and the terminating null, but no more, i.e.:
char fmt[] = "% ";
... gives the following result (which was, perhaps, something like you expected?):
Enter a format specifier: i
23Enter a format specifier: d
23Enter a format specifier: x
17Enter a format specifier: o
27Enter a format specifier: q
q
For more info on this issue you could read Char array initialization dilemma.