与sprintf(snprintf)重叠的内存 [英] Overlapping memory with sprintf(snprintf)
问题描述
如果我们有这个
char value_arr[8];
// value_arr is set to some value
snprintf(value_arr, 8, "%d", *value_arr);
此行为是否已定义?
让我说说我出于某些不合理的原因
Let's say for some ungainly reason I have
char value_arr[8];
// value_arr is set to some value
int* value_i = reinterpret_cast<int*>(value_arr);
snprintf(value_arr, 8, "%d", *value_i); // the behaviour in question
是否可以保证,例如,如果 * value_i
= 7,则 value_arr
将采用"7"的值.是否定义了此行为?这样,首先取消对 value_i
的引用,然后按值传递,然后对其进行格式化,然后将其存储到数组中.
Is there a guarantee that, for example, if *value_i
= 7, then value_arr
will take on the value of "7". Is this behavior defined? Such that value_i
is first dereferenced, then passed by value, and then formatted, then stored into the array.
通常, * value_i
的值不会发生变化,但是将字符串存储到 value_arr
中会违反此规定.
Normally, the value of *value_i
can be expected to not change, but storing the string into value_arr
violates that.
当我测试它时,它似乎可以正常运行,但是我似乎在文档中找不到明确的答案.函数签名具有 ...
,据我所知与 va_list
有关,但是恐怕我对可变函数的工作不是很了解
It seems to function as expected when I test it, but I can't seem to find a definitive answer in the documentation. The function signature has ...
, which to my knowledge has something to do with va_list
, but I'm afraid I'm not very knowledgable on the workings of variadic functions.
int sprintf (char* str, const char* format, ... );
推荐答案
对于原始代码,评估表达式 * value_i
会违反严格的别名规则,从而导致未定义的行为.不允许将char数组别名为 int
.
For the original code, evaluating the expression *value_i
causes undefined behaviour by violating the strict aliasing rule. It is not permitted to alias a char array as int
.
对于已编辑的代码, snprintf(value_arr,8,%d",* value_arr);
很好,它将格式化数组中第一个字符的字符代码.在进入函数之前,对函数自变量的求值是有序的.(C ++ 17 intro.execution/11)
For the edited code, snprintf(value_arr, 8, "%d", *value_arr);
, it is fine and will format the character code of the first character in the array. Evaluation of function arguments is sequenced-before entering the function. (C++17 intro.execution/11)
这篇关于与sprintf(snprintf)重叠的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!