首页 > 解决方案 > 如果格式字符串没有 % 引用,vsprintf() 是否保证不访问 va_list?

问题描述

如果传递给vsprintf()(及其变体)的格式字符串不包含 %-references,是否保证不访问 va_list 参数?

换句话说,是:

#include <stdarg.h>
#include <stdio.h>
int main ( void ) {
    char    str[16];
    va_list ap;         /* never initialized */

    (void)vsnprintf(str, sizeof(str), "", ap);
    return 0;
}

符合标准的程序?还是那里有未定义的行为?

上面的例子显然很愚蠢,但是想象一个可以被可变参数函数和固定参数函数调用的函数,粗略地简化为如下所示:

void somefuncVA ( const char * fmt, va_list ap ) {
    char    str[16];
    int     n;

    n = vsnprintf(str, sizeof(str), fmt, ap);
    /* potentially do something with str */
}

void vfoo ( const char * fmt, ... ) {
    va_list ap;

    va_start(fmt, ap);
    somefuncVA(fmt, ap);
}

void foo ( void ) {
    va_list ap;     /* no way to initialize this */

    somefuncVA("", ap);
}

标签: cprintfvariadic-functions

解决方案


如果您没有将可变参数传递给您的函数 - 您的函数没有定义...为最后一个参数 - 根本不需要在该函数中使用va_listor 。va_start()如果您想传递一组空的变量参数,只需直接调用 varargs 函数而不使用任何变量参数 - 例如,printf("\n");.

例如,而不是

void foo ( void ) {
    va_list ap;     /* no way to initialize this */

    somefuncVA("", ap);
}

你可以写

void foo ( void ) {
    vfoo("");
}

推荐阅读