gpt4 book ai didi

c++ - vsnprintf 返回超过给定缓冲区大小的大小

转载 作者:太空狗 更新时间:2023-10-29 23:49:18 51 4
gpt4 key购买 nike

带有 myPrint() 函数的超长字符串将会崩溃。

我认为 vsnprintf() 无法从 linux 手册页返回超过缓冲区长度的写入大小。

我预期的字符串是缓冲区大小的截断字符串,但这在下面的测试代码中是完全错误的。

下面有什么问题??

void myPrint(const char* fmt, ...)
{
char buffer[512] = {0,};

va_list arg;
va_start(arg, fmt);

int r = vsnprintf(buffer, 511, fmt, arg); // buffer size is given
if (r > 0) // works correctly
buffer[r+1] = '\0'; // crash because r is 200,000
va_end(arg);
}

int main(int, char**)
{
const char * data = "abcdefg...." // assuming that a length is 200,000 byte string
myPrint("%s\n", data);
}

最佳答案

不,vsnprintf非常具体地返回完整字符串所需的字符数。 C11 7.21.6.12p3 :

The vsnprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

此外,输入大小应该是完整的缓冲区大小,例如这里 512。 然后 vsnprintf将写入最多 511 个字符并添加终止 '\0'在写完最后一个字符之后。 (C11 snprintf description) :

Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

此外,请注意 ( 7.21.6.5p2 ):

[...] Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

也就是说,如果您的缓冲区是 512 char 的数组并且您传入了 512,如果返回 n,则字符串已正确写入且未被截断*snprintf 的值是0 <= n <= 511


请注意 Microsoft Visual C++ 有一个名为 _vsnprintf 的非常糟糕的函数那:

[...] return the number of characters written if the number of characters to write is less than or equal to count; if the number of characters to write is greater than count, these functions return -1 indicating that output has been truncated.


最后,如果您只编写 Linux/Glibc 特定代码,您还可以考虑使用 vasprintf这将动态分配一个足够大的缓冲区来容纳整个字符串。

关于c++ - vsnprintf 返回超过给定缓冲区大小的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43178776/

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