va_list shows undefined behavior when passed to another function.
I provided a minimized example based on the codebase i (have to) work on, sample output and steps to reproduce below.
If you have any insight why this happens, I would be glad to hear from you!
Expected behavior:
test
42
3.14
Shown behavior:
On ARM: The int value changes with every execution.
test
1563430200
3.14
On x86: The int value is constant per execution.
test
4202506
3.14
Steps to reproduce:
1.) Copy code example below to "main.cpp"
2.) Build: e.g.: $ g++ main.cpp -Wall -Wpedantic -O0
3.) Execute: $ ./a.out
Disclaimer: The design of the code is bugprone, passing the number of va_args and doing type matching based on the index.
Content of main.cpp:
#include <cstdarg>
#include <cstdint>
#include <iostream>
void process_va_list(const uint64_t argument_index, va_list va) {
va_list va_copy;
va_copy(va_copy, va);
// The commented lines below output the expected value
// std::cout << va_arg(va_copy, const char*) << "\n";
// std::cout << va_arg(va_copy, int) << "\n";
// std::cout << va_arg(va_copy, double) << "\n";
if (argument_index == 0) {
std::cout << va_arg(va_copy, const char *) << "\n";
} else if (argument_index == 1) {
std::cout << va_arg(va_copy, int) << "\n";
} else if (argument_index == 2) {
std::cout << va_arg(va_copy, double) << "\n";
}
va_end(va_copy);
}
void va_function(uint64_t number_of_vargs, ...) {
va_list args;
va_start(args, number_of_vargs);
for (uint64_t argument_index = 0; argument_index < number_of_vargs;
argument_index++) {
process_va_list(argument_index, args);
}
va_end(args);
}
int main() {
const uint64_t number_of_vargs = 3;
va_function(number_of_vargs, "test", 42, 3.14);
return 0;
}
Edit: syntax highlighting in discord
Edit: add missing cstdint