为什么vsnprintf不写与strncpy相同数量的字符? [英] Why is vsnprintf Not Writing the Same Number of Characters as strncpy Would?

查看:161
本文介绍了为什么vsnprintf不写与strncpy相同数量的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问过关于strncpy 的相同问题,但是string最终包含了全部内容输入字符串.将字符串传递给vsnprintf时,最后一个字符总是会被砍掉: https://rextester.com/UIQMX91570

I've asked the same question about strncpy, but there the string ends up containing the whole input string. When passing a string to vsnprintf the last character always gets chopped off: https://rextester.com/UIQMX91570

为简单起见,我还在代码的内联上方包含了实时示例链接:

For simplicity I've also included the live example link above inline in the code:

void bar(const char* format, va_list vlist) {
    const auto buf_size = vsnprintf(nullptr, 0U, format, vlist);
    string buffer(buf_size, '\0');

    vsnprintf(data(buffer), buf_size, format, vlist);
    cout << data(buffer) << endl;
}

void foo(const char* format, ...) {
    va_list vlist;

    va_start(vlist, format);
    bar(format, vlist);
    va_end(vlist);
}

如果我用foo("lorem ipsum %d", 13)进行调用,我得到的输出是:

If I call this with: foo("lorem ipsum %d", 13) the output I get is:

lorem ipsum 1

lorem ipsum 1

如我所料:lorem ipsum 13

Where as I would have expected: lorem ipsum 13

谁能解释这个差异?当我调试时,得到的buf_size为14,其中应该足以包含整个字符串,但它不是:(

Can anyone explain the discrepancy? When I debug I get a buf_size of 14 which should be enough to contain the entire string, yet it does not :(

推荐答案

任何人都可以解释差异吗?

Can anyone explain the discrepancy?

因为他们记录的行为不同.

Because their documented behavior is different.

strncpy()

如果在复制整个数组src之前已达到计数,则生成的字符数组不能为空终止.

但是 vsnprintf()

最多写入buf_size-1个字符. 结果字符串将以空字符结尾,除非buf_size为零.

强调是我的.

这篇关于为什么vsnprintf不写与strncpy相同数量的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆