Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum characters printable by printf in C

In C's printf function in using this gigantic string formatter width sub-specifier; close to the standard's limit a positive signed int; which is provided below the rest of the string formats are ignored.

Example String format:

printf("**%2147483614p %1073739618p This text and %d formatters are ignored!!! why**", &i, &j, 10);

output: **2147483614 empty spaces0xbf****** 1073739618 empty spaces

Problem:

The text "**This text and 10 formatters are ignored!!! why****" and the integer 10 does not show up on screen. It prints the full of the first %p with its padding and the padding created by the width specifier for the second %p but no pointer and rest of string to be printed.

Note: the second pointer can be made to be printed by left adjusting the format specifier like

printf("%-2147483614p %-1073739618p This text and %d formatters are ignored!!! why**", &i, &j, 10);**

but still the strings after are still missing.

The code

#include <stdio.h>

int main(int argc, char const *argv[]){
    printf(argv[1]);
    return 0;
}

x86_64-linux-gnu gcc version 7.3.0

gcc printf.c -o printf

./printf "%-2147483614p %-1073739618p This text and %d formatters are ignored!!! why"

P.S. I am aware this is a memory leak


Found out %29p (29 is the max, 30 would not print) for second pointer prints the rest of the string. but if there is another format sting in the rest of the string it stops there.

like image 691
Eyosias Negash Avatar asked Jan 28 '23 03:01

Eyosias Negash


1 Answers

If you are asking specifically about the maximum width specifier, according to the C Standard, §7.21.6.1.15 (which describes fprintf; printf is described later as a specific case of fprintf):

The number of characters that can be produced by any single conversion shall be at least 4095.

This means that if, as you report, the maximum width that your C implementation's printf can handle for a format specifier before it stops working as expected is 0x7fffffe2, this is acceptable, since that satisfies the requirement of at least 4095 characters.

As for the remainder of the string not being printed out, without an MCVE, I would hazard a guess at it being a side effect of having such nonsensical width values earlier in the string. Also, %D is not a valid format specifier.

like image 51
Govind Parmar Avatar answered Feb 07 '23 19:02

Govind Parmar