Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use va_list in exception-prone code?

Tags:

c++

Typical example:

void foo(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);

    // might throw, might not.  who knows.
    bar(fmt, args);

    // uh-oh...
    va_end(args);
}

Is this a bad idea, i.e. is it uncommon to use va_list in c++? If I wrap bar in a try-catch, does that help? What would be some alternatives?

like image 652
jwalk Avatar asked Jul 18 '13 18:07

jwalk


1 Answers

The C++ standard defers to the C standard for the specification of va_start et al. The C standard has this to say:

7.15.1p1 ...Each invocation of the va_start and va_copy macros shall be matched by a corresponding invocation of the va_end macro in the same function.

Thus, if you exit the function by any means after calling va_start but before va_end, your program exhibits undefined behavior.

Yes, wrapping bar in a try/catch would help.

like image 180
Igor Tandetnik Avatar answered Sep 20 '22 00:09

Igor Tandetnik