The variable arguments passed to a variadic function are accessed by calling the
va_arg() macro. This macro accepts the
va_list representing the variable arguments of the function invocation and the type denoting the expected argument type for the argument being retrieved. The macro is typically invoked within a loop, being called once for each expected argument. However, there are no type safety guarantees that the type passed to
va_arg matches the type passed by the caller, and there are generally no compile-time checks that prevent the macro from being invoked with no argument available to the function call. The C Standard, 184.108.40.206, states [ISO/IEC 9899:2011], in part:
If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases:
— one type is a signed integer type, the other type is the corresponding unsigned integer type, and the value is representable in both types;
— one type is pointer to
voidand the other is a pointer to a character type.
Ensure that an invocation of the
va_arg() macro does not attempt to access an argument that was not passed to the variadic function. Further, the type passed to the
va_arg() macro must match the type passed to the variadic function after default argument promotions have been applied. Either circumstance results in undefined behavior.
Noncompliant Code Example
The compliant solution accesses the variadic argument with type
int, and then casts the resulting value to type
Noncompliant Code Example
Standard C provides no mechanism to enable a variadic function to determine how many variadic arguments are actually provided to the function call. That information must be passed in an out-of-band manner. Oftentimes this results in the information being encoded in the initial parameter, as in this compliant solution:
Incorrect use of
va_arg() results in undefined behavior that can include accessing stack memory.
|Axivion Bauhaus Suite|
|Can detect some instances of this rule, such as promotable types.|
Cannot detect mismatched types or incorrect number of variadic arguments.
|BADMACRO.STDARG_H||Use of <stdarg.h> feature|
|LDRA tool suite|
|CERT_C-EXP47-a||Do not call va_arg with an argument of the incorrect type|
Data type of variadic function argument does not match type in va_arg call
Number of va_arg calls exceeds number of arguments passed to variadic function
|[ISO/IEC 9899:2011]||Subclause 7.16, "Variable Arguments |
Subclause 220.127.116.11, "Function calls"