Pass va_list or pointer to va_list?

前端 未结 6 885
遇见更好的自我
遇见更好的自我 2020-12-01 12:22

Suppose I have a function which takes variadic arguments (...) or a va_list passed from another such function. The main logic is in this function i

6条回答
  •  温柔的废话
    2020-12-01 12:54

    You should pass a pointer to a va_list if you want to use it in a subfunction and then not have to immediately pass it to va_end afterwards. From C99:

    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.

    The standard allows this, however, on some 64-bit platforms where va_list is an array type, this does not work. As the address of an array is the same as the address of the first element of the array, passing a pointer to the va_list will segfault upon calling va_arg with that pointer to va_list as an argument.

    A way to get around this is by receiving the va_list as an unconventional argument name (usually suffixed with one or more underscores) and then creating a new local va_list, like so:

    #include 
    
    int vfoo(va_list ap_)
    {
        int ret;
        va_list ap;
        va_copy(ap, ap_);
        ret = vbar(&ap);
        /* do other stuff with ap */
        va_end(ap);
        return ret;
    }
    

    This is the approach I use in my vsnprintf implementation to call other functions from it for formatting.

提交回复
热议问题