加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如果格式字符串没有%引用,vsprintf()是否保证不访问va_list?

发布时间:2020-12-16 09:21:18 所属栏目:百科 来源:网络整理
导读:如果传递给vsprintf()的格式字符串(及其变体)不包含%-references,是否可以保证不访问va_list参数? 换句话说,是: #include stdarg.h#include stdio.hint main ( void ) { char str[16]; va_list ap; /* never initialized */ (void)vsnprintf(str,sizeof(s
如果传递给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;
}

符合标准的计划?或者那里有不确定的行为吗?

上面的例子显然是愚蠢的,但想象一下可以通过可变参数函数和fixed-args函数调用的函数,大致简化为:

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

    n = vsnprintf(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);
}

解决方法

int vsprintf(char * restrict s,const char * restrict format,va_list arg);

If the format string passed to vsprintf() … contains no %-references,is it guaranteed that the va_list argument is not accessed.

没有.

The vsprintf function is equivalent to sprintf,with the variable argument list
replaced by arg,which shall have been initialized by the va_start macro …..
C11dr §7.21.6.13

由于以下代码不符合规范,因此结果是未定义的行为(UB).没有保证. @Eugene Sh.

va_list ap;
//                                    vv-- ap not initialized
(void)vsnprintf(str,ap);

Is vsprintf() guaranteed not to access va_list if format string makes no % references?

通过正确传递的va_list arg,vsprintf()就像sprintf()一样.像下面的代码是可以的.允许传递额外的参数.通过vsprintf(),不访问它们(额外参数),但可以访问va_list arg.

sprintf(buf,"format without percent",1.2345,456)`

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读