printf() 的字符串宽度对于未终止的字符串是否安全?
Is printf()'s string width safe with unterminated strings?
下面的定义是否明确?
const char not_a_c_string[] = { 'h', 'e', 'l', 'l', 'o' };
printf( "%.5s", (const char*) not_a_c_string );
这是一个关于特定形式 "%.5s"
的问题,而不是 如何打印可能不以 NUL 结尾的字符串? 因为这个问题有 already been answered here 建议使用 "%.*s"
结构。
首先,我相信,您是想询问 精度,而不是 字段宽度。所以,你的例子看起来像
printf( "%.5s", (const char*) not_a_c_string ); //precision
而不是
printf( "%5s", (const char*) not_a_c_string ); //field width.
考虑到上面的做法,不,在你的例子中不会是UB。
引用 C11
标准,第 §7.21.6.1 章,fprintf
函数,第 8 段,(强调我的)
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.
因此,仅当您是
- 缺少精度
- 提供的精度是
>
提供的 char
数组的大小。
在您的情况下,提到的精度 (5) 不大于 数组的大小(也是 5)。所以,没关系。
FWIW,如果示例仍然存在
printf( "%5s", (const char*) not_a_c_string );
那么它将是 UB,因为你在那里会缺少精度。
下面的定义是否明确?
const char not_a_c_string[] = { 'h', 'e', 'l', 'l', 'o' };
printf( "%.5s", (const char*) not_a_c_string );
这是一个关于特定形式 "%.5s"
的问题,而不是 如何打印可能不以 NUL 结尾的字符串? 因为这个问题有 already been answered here 建议使用 "%.*s"
结构。
首先,我相信,您是想询问 精度,而不是 字段宽度。所以,你的例子看起来像
printf( "%.5s", (const char*) not_a_c_string ); //precision
而不是
printf( "%5s", (const char*) not_a_c_string ); //field width.
考虑到上面的做法,不,在你的例子中不会是UB。
引用 C11
标准,第 §7.21.6.1 章,fprintf
函数,第 8 段,(强调我的)
s
If nol
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.
因此,仅当您是
- 缺少精度
- 提供的精度是
>
提供的char
数组的大小。
在您的情况下,提到的精度 (5) 不大于 数组的大小(也是 5)。所以,没关系。
FWIW,如果示例仍然存在
printf( "%5s", (const char*) not_a_c_string );
那么它将是 UB,因为你在那里会缺少精度。