printf : Is this safe?

后端 未结 3 707
陌清茗
陌清茗 2021-01-14 01:52

I am just wondering if this expression is safe :

int main (void)
{
  char my_tab[256];

  memset(my_tab,0x61,sizeof(my_tab));

  printf(\"Is it safe ? : %.2         


        
3条回答
  •  滥情空心
    2021-01-14 02:18

    Yes, you will print out 256 characters, and nothing more.

    From the C11-Standard 7.21.6. p4:

    An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of bytes to be written for s conversions. The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero. If a precision appears with any other conversion specifier, the behavior is undefined.

    7.21.6.1. p8:

    s : If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. 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.

提交回复
热议问题