二楼的方法并不安全!!
在使用二楼的非固定参数方法时遇到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)