Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

c++ - Why is vsnprintf Not Writing the Same Number of Characters as strncpy Would?

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, '');

    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);
}

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

lorem ipsum 1

Where as I would have expected: lorem ipsum 13

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 :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because man page clearly says that

If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '') which would have been written to the final string if enough space had been available.

If you'd check the return value of your second vsnprintf call, you'd see that return value is equal to the size, as in the man page:

Thus, a return value of size or more means that the output was truncated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...