Main Content

Invalid va_list argument

Variable argument list used after invalidation with va_end or not initialized with va_start or va_copy

Description

This defect occurs when you use a va_list variable as an argument to a function in the vprintf group but:

  • You do not initialize the variable previously using va_start or va_copy.

  • You invalidate the variable previously using va_end and do not reinitialize it.

For instance, you call the function vsprintf as vsprintf (buffer,format, args). However, before the function call, you do not initialize the va_list variable args using either of the following:

  • va_start(args, paramName). paramName is the last named argument of a variable-argument function. For instance, for the function definition void func(int n, char c, ...) {}, c is the last named argument.

  • va_copy(args, anotherList). anotherList is another valid va_list variable.

Risk

The behavior of an uninitialized va_list argument is undefined. Calling a function with an uninitialized va_list argument can cause stack overflows.

Fix

Before using a va_list variable as function argument, initialize it with va_start or va_copy.

Clean up the variable using va_end only after all uses of the variable.

Examples

expand all

#include <stdarg.h>
#include <stdio.h>

int call_vfprintf(int line, const char *format, ...) {
    va_list ap;
    int r=0;
    
    va_start(ap, format);
    r = vfprintf(stderr, format, ap);
    va_end(ap);

    r += vfprintf(stderr, format, ap);
    return r;
}

In this example, the va_list variable ap is used in the vfprintf function, after the va_end macro is called.

Correction — Call va_end After Using va_list Variable

One possible correction is to call va_end only after all uses of the va_list variable.

#include <stdarg.h>
#include <stdio.h>

int call_vfprintf(int line, const char *format, ...) {
    va_list ap;
    int r=0;
    
    va_start(ap, format);
    r = vfprintf(stderr, format, ap);
    r += vfprintf(stderr, format, ap);
    va_end(ap);
    
    return r;
}

Result Information

Group: Programming
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: INVALID_VA_LIST_ARG
Impact: High

Version History

Introduced in R2015b