我正在尝试为sprintf来自cstdio. 但是,在运行我的程序时,我遇到了一些奇怪的行为和访问冲突崩溃。我已经简化了问题并在下面的代码中重现了它:
#include <string>
#include <cstdio>
#include <cstdarg>
std::string vfmt(const std::string& format, va_list args)
{
    int size = format.size() * 2;
    char* buffer = new char[size];
    while (vsprintf(buffer, format.c_str(), args) < 0)
    {
       delete[] buffer;
       size *= 2;
       buffer = new char[size];
    }
    return std::string(buffer);
}
std::string fmt(const std::string& format, ...)
{
    va_list args;
    va_start(args, format);
    std::string res = vfmt(format, args);
    va_end(args);
    return res;
}
int main()
{
    std::string s = fmt("Hello %s!", "world");
    printf(s.c_str());
    return 0;
}
vsprintf此代码在调用时会产生内存访问冲突vfmt。但是,当我将fmt的函数签名从更改fmt(const std::string& format, ...)为 时fmt(const char* format, ...),我不再崩溃,并且一切都按预期工作。为什么会发生这种情况?
为什么将format参数的类型从更改const std::string&为const char*解决问题?或者它似乎只是被解决了?