Understanding va_list in Variadic Functions: gp_offset Incrementation, fp_offset Fixation, and Garbage Values

104 Views Asked by At

In variadic functions, the va_list type is often implemented as an array of structs, where each array element holds a struct with the following definition:

typedef struct {
   unsigned int gp_offset;
   unsigned int fp_offset;
   void *overflow_arg_area;
   void *reg_save_area;
} va_list[1];

I noticed interesting behavior when using va_list in a simple code snippet:

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

void example_function(int arg_count, ...) {
    va_list args;
    va_start(args, arg_count);

    int i = 0;
    while (i < arg_count) {
      printf("%d\n", va_arg(args, int));
      i++;
    }

    va_end(args);
}

int main() {
    example_function(3, 1, 2, 3);
    return 0;
}

In this code:

  1. The gp_offset starts at 8 and increments by 8 with each call to va_arg in the while loop.
  2. The fp_offset remains fixed at 48.
  3. overflow_arg_area and reg_save_area are initialized with garbage values.

I would like to understand:

  • Why does gp_offset increment by 8 with each va_arg call?
  • Why is fp_offset fixed at 48?
  • Why do overflow_arg_area and reg_save_area point to garbage values?
0

There are 0 best solutions below