stdarg c语言,C 标准库 – <stdarg.h> | 菜鸟教程

二楼的方法并不安全!!

在使用二楼的非固定参数方法时遇到bug,我传递的参数是结构体指针,代码如下:

void AddChildren(Node* parent, ...)

{

if (parent == NULL) return;

Node* child = NULL;

va_list child_list;

va_start(child_list, parent);

while (child = va_arg(child_list, Node*)) {

parent->children[parent->child_ptr++] = child;

}

va_end(child_list);

child = NULL;

}

但是在打印树结构时,报错

Segmentation fault (core dumped)

我当时并不清楚错误产生的原因,而当我修改该函数为:

void AddChildren(Node* parent, int childnum, ...)

{

if (parent == NULL) return;

va_list child_list;

va_start(child_list, childnum);

for (int i = 0; i < childnum; i++) {

parent->children[parent->child_ptr++] = va_arg(child_list, Node*);

}

va_end(child_list);

}

之后代码可以正确运行。

部分内容摘录如下:

Don't use va_list, especially in member functions. And you need to know the number of the arguments, va_arg will happily read the entire memory if it can。

所以一种解决方案是像我上面那样传入确定的参数个数。

而另一位老哥给出了另一种解决方案,即仍旧使用二楼类似的代码,但在传递参数时额外传递一个0,作为while判断的终止符号:

Variadic function arguments are not typesafe, or any kind of 'safe' for that matter. It is your responsibility to communicate to your function how many arguments there are and what their types are.

In your code, the only thing that makes the loop terminate is when x evaluates as false. Your data, obscurely typed as it is, seems to consist of integral values, and that would necessitate your last variadic argument to be zero, which it isn't in your example.

Try calling the function wtih (n, x1, x2, x3, 0).

一点星光

一点星光

ist***hang@outlook.com2个月前 (03-19)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值