传递va_list*会不会导致标准未定义问题?

whoho 2008-01-16 08:53:26
C99上写明,如果传递va_list给函数,如果函数内部对va_list调用了va_arg(),
则函数调用返回以后,不应再对其调用va_arg()

如果传递的是va_list*,则函数返回后,是否可以继续对其调用va_arg()?

给定:
void fun(va_list arg)
{
va_arg(arg, int);
}

void gun(va_list* arg)
{
va_arg(*arg, int);
}


则:
(1)标准写明的情况:
//假设arg已经用va_start初始化过
for (i=0; i<4; i++)
fun(arg);
这段调用是不允许的
(2)这是我有疑问的:
//假设arg已经用va_start初始化过
for (i=0; i<4; i++)
gun(arg);
这样子是否可以?


如果是要在一个编译器上做个实验,那对我意义不大,现在我需要在几个平台上做可移植的代码。
所以请尽量以标准的角度来给我解释一下,谢谢。

...全文
172 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
whoho 2008-01-21
  • 打赏
  • 举报
回复
太好了,谢谢
找了半天原来这句话是一句脚注:
212) It is permitted to create a pointer to a va_list and pass that pointer to another function, in which
case the original function may make further use of the original list after the other function returns.

CrySleeper 2008-01-20
  • 打赏
  • 举报
回复
C99只是说,
fun(arg);
va_arg(arg, int); 这种情况下得到的值可能已经被fun改动了,至少肯定是被fun使用过了

原文如下:
The object ap may be passed as an argument to another function;
if that function invokes the va_arg macro with parameter ap, the value of ap in the
calling function is indeterminate and shall be passed to the va_end macro prior to any
further reference to ap

而通过valist*,va_arg(arg, int)就不会访问gun使用过的参数,而是访问gun使用的参数后面的参数
原文如下
It is permitted to create a pointer to a va_list and pass that pointer to another function, in which
case the original function may make further use of the original list after the other function returns.
goodluckyxl 2008-01-18
  • 打赏
  • 举报
回复
可以吧 va_list 也就是char*
操作的地址内容在其他位置
应该无关局部栈的变化
FigoZhu 2008-01-18
  • 打赏
  • 举报
回复
帮顶,接分。
Treazy 2008-01-16
  • 打赏
  • 举报
回复
手边没有标准,不能详细查一下

不过按照我的个人理解
如果你的程序是用函数去调用va_arg
并且parg已经初始化,这是完全可以的,但是这样的代码看上去怪怪的
而且也容易产生问题!

因为你va_end没有出现,增加了很多不确定性

另外你的代码正确的调用形式应该是这样的


va_list pArg;
va_start(pArg, Arg);
for(int i = 0; i<XXX; i++)
{
gun(&pArg, TYPE);
.../*other function*/
}
va_end(pArg);
whoho 2008-01-16
  • 打赏
  • 举报
回复
例子可以简明一点:
(1)C99规定不允许的情形
fun(arg);
va_arg(arg, int);
(2)我有疑问的:是否可以这样?
gun(&arg);
va_arg(arg, int);


原帖子的gun(arg)应该是gun(&arg),属笔误

69,377

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧