user2793162
user2793162

Reputation:

sprintf undefined behaviour

I can't seem to find info on this: Does using wrong format specifiers in sprintf cause UB like in printf?

and I'll ask also here is following UB?

unsigned int x = 5;
printf("%d",x);

or this:

unsigned char x = 5;
printf("%d",x);

Upvotes: 1

Views: 273

Answers (1)

T.C.
T.C.

Reputation: 137394

Does using wrong format specifiers in sprintf cause UB like in printf?

Yes. All the *printf specifiers are defined the same (in the fprintf section, actually).

and I'll ask also here is following UB?

unsigned int x = 5;
printf("%d",x);

This is technically UB. %d expects an int argument, and "If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." (WG14 N1570, 7.21.6.1/p9; I don't think C11 changed anything here compared to C99). unsigned int is not int. In practice, you can probably get away with it.

or this:

unsigned char x = 5;
printf("%d",x);

This is not UB if and only if unsigned char is promoted to int by integer promotion, which is usually the case.

Upvotes: 6

Related Questions