使用未终止的字符串,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终止的字符串?,因为此问题具有构造.
This is a question about the specific form "%.5s"
, and not an how to print a possibly not NUL-terminated string? as this question has already been answered here where the "%.*s"
construct is suggested.
推荐答案
首先,我认为,您要问的是精度,而不是字段宽度 .因此,您的示例看起来像
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
代替
printf( "%5s", (const char*) not_a_c_string ); //field width.
考虑到上述方法,不,在您的示例中它将不是UB.
Considering the above approach, no, it will not be UB in your example.
要引用C11
标准,请参见第§7.21.6.1章 fprintf
函数,第8段,(强调我的)
To quote the C11
standard, chapter §7.21.6.1, The fprintf
function, paragraph 8, (emphasis mine)
s
如果不存在l
长度修饰符,则该参数应为指向初始值的指针 字符类型数组的元素.(280)数组中的字符是 写入(但不包括)终止空字符.如果 指定了精度,但写入的字节数不超过该字节数. 如果 没有指定精度或大于数组的大小,数组应 包含空字符.
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.
因此,只有当您是其中一个时,才需要使用以空值分隔的数组( string )
So, you need to have a null delimited array (string) only if you're either
- 缺少精度
- 提供的精度为
>
所提供的char
数组的大小.
- missing the precision
- supplied precision is
>
the size of the suppliedchar
array.
在您的情况下,提到的精度(5)不大于数组的大小(也为5).所以,很好.
In your case, the mentioned precision (5) is not greater that the size of the array (also 5). So, It's fine.
FWIW,如果示例仍然存在
FWIW, if the example remains
printf( "%5s", (const char*) not_a_c_string );
那么它将是UB,因为您在那里会失去精度.
then it will be UB, as you'll be missing precision there.
这篇关于使用未终止的字符串,printf()的字符串宽度安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!