gpt4 book ai didi

到目前为止在 snprintf 中写入的字符

转载 作者:太空狗 更新时间:2023-10-29 17:07:40 27 4
gpt4 key购买 nike

最近,我注意到一个奇怪的案例,我想验证一下:

通过 SUS,对于格式字符串中的 %n,相应的 int 将被设置为 the-amount-of-bytes-written-to-the-output .此外,对于 snprintf(dest, 3, "abcd")dest 将指向 "ab\0"。为什么?因为要将不超过 n (n = 3) 个字节写入输出(dest 缓冲区)。

我为代码推断出:

int written;
char dest[3];
snprintf(dest, 3, "abcde%n", &written);

written 将设置为 2(从计数中排除空终止)。但是根据我使用 GCC 4.8.1 进行的测试,written 设置为 5。我误解了标准吗?这是一个错误吗?这是未定义的行为吗?

编辑:

@wildplasser 说:

... the behavior of %n in the format string could be undefined or implementation defined ...

... the implementation has to simulate processing the complete format string (including the %n) ...

@par 说:

written is 5 because that's how many characters would be written at the point the %n is encountered. This is correct behavior. snprintf only copies up to size characters minus the trailing null ...

和:

Another way to look at this is that the %n wouldn't have even been encountered if it only processed up to 2 characters, so it's conceivable to expect written to have an invalid value...

和:

... the whole string is processed via printf() rules, then the max-length is applied ...

是否可以验证它是标准、标准草案还是某些官方来源?

最佳答案

written 是 5,因为这是在遇到 %n 时要写入的字符数。这是正确的行为。 snprintf 只复制最多 size 个字符减去尾随的 null(所以在你的情况下 3-1 == 2。你必须将字符串格式化行为与 only-write 分开-这么多字符。

另一种看待这个问题的方法是,如果 %n 只处理最多 2 个字符,它甚至不会遇到,所以可以想象 written具有无效值。如果您期望在遇到 %n 时在 written 中有效(但没有),那么这就是错误所在。

所以请记住,整个字符串是通过 printf() 规则处理的,然后应用最大长度。

关于到目前为止在 snprintf 中写入的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25556109/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com