c - 如果格式字符串没有 % 引用,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);
}
解决方案
如果您没有将可变参数传递给您的函数 - 您的函数没有定义...
为最后一个参数 - 根本不需要在该函数中使用va_list
or 。va_start()
如果您想传递一组空的变量参数,只需直接调用 varargs 函数而不使用任何变量参数 - 例如,printf("\n");
.
例如,而不是
void foo ( void ) {
va_list ap; /* no way to initialize this */
somefuncVA("", ap);
}
你可以写
void foo ( void ) {
vfoo("");
}
推荐阅读
- c++ - 处理来自 IMFSourceReader 和 IMFSample 的图像数据
- c# - 在 Unity 运行时将图像导入资源文件夹
- python-3.x - 策略中的 AWS Boto3 语法错误
- vba - 如何每隔四个分隔符拆分一个字符串?
- java - 尝试拆分从用户扫描的 Java 中的字符串
- linux - Linux - 在 runlevel3 中启动并添加 X11 组件
- c - 将数组复制到另一个数组(字符串)中,在C中复制其内容
- powershell - 无法使用接收到的继续令牌进行迭代
- r - R,bookdown 包,在 R 块中强制 LaTex
- python - Matplotlib - 结合文本/注释坐标系