简体   繁体   English

可变参数列表打印垃圾

[英]Variable argument list prints garbage

Following function prints garbage on console.以下函数在控制台上打印垃圾。 Cannot understand the issue.无法理解问题。 Below is a test code fragment.下面是一个测试代码片段。

void
format(
    const char* pcszFormat,
    ...
    )
{
    va_list VarArglist;

    va_start(VarArglist, pcszFormat);
    printf(pcszFormat, VarArglist);
    va_end(VarArglist);
}


int wmain(int argc, wchar_t *argv[])
{
    string strTest;
    const char *pcszFormatted;

    format("%x %S", 10, "Test");

    //printf("\nFormatted string: %s", pcszFormatted);
    getchar();
    return 0;
}

You invoked undefined behavior by passing data having wrong type to printf() .您通过将类型错误的数据传递给printf()来调用未定义的行为 You should use vprintf() to work with va_list .您应该使用vprintf()来处理va_list

Also don't forget to change %S to %s in order to work with normal string or change "Test" to L"Test" in order to work with wide string, or you will invoke undefined behavior by passing data having wrong type to printf() family again.另外不要忘记将%S更改为%s以使用普通字符串或将"Test"更改为L"Test"以使用宽字符串,否则您将通过将错误类型的数据传递给调用未定义的行为printf()家族又来了。

You can't pass va_list to printf .您不能将va_list传递给printf Use vprintf instead.请改用vprintf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM