Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

A variadic function – a function declared with a parameter list ending with ellipsis (...) – can accept a varying number of arguments of varying types. Variadic functions are flexible, but they are also hazardous. The compiler can't verify that a given call to a variadic function passes an appropriate number of arguments or that those arguments have an appropriate typetypes. Consequently, a runtime call to a variadic function that passes inappropriate arguments yields undefined behavior. Such undefined behavior could be exploited to run arbitrary code.When a function call appears in some contexts, notably as the argument in a sizeof expression, the compiler

Non-

...

compliant Code Example

Code Block
bgColor#FFCCCC

// in translation unit A:
extern char const *const term;
bool isVT100 = strcmp( term, "VT100" ) == 0;

// in translation unit B:
char const * const term = getenv( "TERM" );

In the example above, there is no way to guarantee that the external term object is initialized by the call to getenv before its value is accessed by the initializer for isVT100.

Compliant Solution

An appropriate coding or design technique should be used to avoid the runtime static initialization of namespace scope objects. The best solution is often simply to avoid using such variables, to the extent practical.

Code Block
bgColor#ccccff

When a function call appears in some contexts, notably as the argument in a sizeof expression, the compiler performs overload resolution to determine the result type of the call, but the object code doesn't execute the call at runtime. In that case, calling a variadic function does no harm, and can actually be very useful.

Compliant Code Example

Code Block
bgColor#ccccff

typedef char True;
typedef struct { char a[2]; } False;

template <typename T>
True isPtr(T *);

False isPtr(...);

#define is_ptr(e) (sizeof(isPtr(e)) == sizeof(True))
// in translation unit A:
extern char const *const term();
bool isVT100() {
    static bool is = strcmp( term(), "VT100" ) == 0;
    return is;
}

//in translation unit B:
char const *const term() {
    static char const * const theTerm = getenv( "TERM" );
    return theTerm;
}

Risk Assessment

Incorrectly using a variadic function can result in abnormal program termination or unintended information disclosure.

...