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:
- The
gp_offsetstarts at 8 and increments by 8 with each call to va_arg in the while loop. - The
fp_offsetremains fixed at 48. overflow_arg_areaandreg_save_areaare initialized with garbage values.
I would like to understand:
- Why does
gp_offsetincrement by 8 with eachva_argcall? - Why is
fp_offsetfixed at 48? - Why do
overflow_arg_areaandreg_save_areapoint to garbage values?