1

After I run this do/while loop for the first time the output always seems to have an extra space before the printf. I think it might have something to do with buffer overflow, but I'm not quite sure how to get rid of it.

Any help would be much appreciated, thanks!

do {
   printf("Enter a format specifier: ");
   scanf(" %c", fmt+1);
   printf(fmt, value);
} while(*(fmt+1) != 'q');

**fmt is a char array.

User97693321
  • 3,336
  • 7
  • 45
  • 69
nohalon
  • 25
  • 2

1 Answers1

0

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.

Community
  • 1
  • 1
Simon
  • 10,679
  • 1
  • 30
  • 44