Is printf () a string width safe with unchanged strings?

Are the following clearly defined?

const char not_a_c_string[] = { 'h', 'e', 'l', 'l', 'o' };
printf( "%.5s", (const char*) not_a_c_string );

This is a question about a specific form "%.5s", not about how to print a line that may not be NUL-terminated? since this question has already been here where the design is proposed "%.*s".

+4
source share
1 answer

First of all, I suppose you wanted to ask about accuracy, not field width. So your example should look like

 printf( "%.5s", (const char*) not_a_c_string );  //precision

instead

 printf( "%5s", (const char*) not_a_c_string );   //field width.

Given the above approach, no, this will not be UB in your example.

C11, §7.21.6.1, fprintf, 8 ( )

s               l, . (280) ( ) . , , . , .

, (string),

  • > char.

(5) , ( 5). , .


FWIW,

 printf( "%5s", (const char*) not_a_c_string );

UB, .

+11

Source: https://habr.com/ru/post/1623967/


All Articles