Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf() - printed characters limit

Tags:

c++

c

printf

I am trying to find what is the allowed limit for the number of characters to be printed by printf() in the C standard. I only found the answer in a discussion forum, which indicates INT_MAX.

For example, I checked the following:

#include <stdio.h>

// INT_MAX  2147483647

int main()
{
    int x=3;

    int y = printf("%2147483647d \n\n", x); --> Confirms INT_MAX ?

    // If I change the above to 2147483648, y in set to -1
    printf("y = %d\n\n", y);

    return 0;
} 

I wanted to ask why is printf() limited by INT_MAX ? Can anyone point out a C standard reasoning or source code reference ?

Edit

The closest answer I found was for fprintf(). At this link, on page 568, its mentioned (under undefined behavior):

The number of characters or wide characters transmitted by a formatted output
function (or written to an array, or that would have been written to an array) is 
greater than INT_MAX.

Will the above justify for printf() as well ?

like image 750
Jake Avatar asked Apr 29 '16 07:04

Jake


2 Answers

printf is stated to return number of characters printed or -1 in case or an error. Its return type is int. Maximum number you can store is int is INT_MAX.

What happens if you try to print more characters? Then printf cannot fulfill its contract: to return number of characters written. Standard does not says what to do when contract is impossible to fulfill, so the behavior in this case is undefined by not being defined in standard.

like image 178
Revolver_Ocelot Avatar answered Oct 18 '22 01:10

Revolver_Ocelot


Well, if you print with the format specifier %d, which indicates a integer number, of course your maximum printable number would be INT_MAX. But your example is wrong. You are trying to tell it to print INT_MAX digits on a number, but that, of course, far exceeds the actual numerical value INT_MAX.

As to why your example fails, I suppose printf() stores the amount of digits to print in an integer number itself.

like image 1
Magisch Avatar answered Oct 18 '22 01:10

Magisch