Is printf()'s string width safe with unterminated strings?

后端 未结 1 1252
无人共我
无人共我 2021-01-19 00:11

Is the following well defined?

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


        
相关标签:
1条回答
  • 2021-01-19 00:35

    First of all, I believe, you meant to ask about the precision, not the field width. So, your example is to look like

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

    instead of

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

    Considering the above approach, no, it will not be UB in your example.

    To quote the C11 standard, chapter §7.21.6.1, The fprintf function, paragraph 8, (emphasis mine)

    s               If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type.(280) Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character.

    So, you need to have a null delimited array (string) only if you're either

    • missing the precision
    • supplied precision is > the size of the supplied char array.

    In your case, the mentioned precision (5) is not greater that the size of the array (also 5). So, It's fine.


    FWIW, if the example remains

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

    then it will be UB, as you'll be missing precision there.

    0 讨论(0)
提交回复
热议问题