Question

Do the C standards give any excuse for the program below not to produce gigabytes of spaces on its standard output?

#include <stdio.h>

int main()
{
  // 2^64 = 18446744073709551616
  printf("x%18446744073709551619dx\n", 42);
  return 0;
}

Tested on Mac OS X 10.8 and on Linux, I get x 42x.

The C11 standard says (7.21.6.1:4): “An optional minimum field width. If the converted value has fewer characters than the field width, it is padded with spaces (by default) on the left (or right, if the left adjustment flag, described later, has been given) to the field width. The field width takes the form of an asterisk * (described later) or a nonnegative decimal integer.”

The wording in C99 is the same.

When the field width is given as *, then the corresponding argument is obtained as an int (7.12.6.1:5). But it does not seem to be said that the hardcoded field width should fit in an int.

Was it helpful?

Solution

Although it doesn't address the specific question of the field width encoding limit, note that §7.21.6.1/15 states "The number of characters that can be produced by any single conversion shall be at least 4095." So even if an implementation does parse 2^64 + 3 correctly, it's conforming to output 4094 spaces instead of "gigabytes".

OTHER TIPS

Although the C standard does not define a maximum value I guess that every compiler has a maximum value for it.

Here is a similar question: size limit of printf conversion specification

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top