I'm using alloca() inside a variadic function to allocate stack memory dynamically based on an integer argument. However, I'm concerned about what happens if the argument is mismatched (e.g., passing a non-integer like a string instead of an int).
Since alloca() adjusts the stack pointer dynamically, could this lead to stack corruption, undefined behaviour, or security vulnerabilities if the argument is misinterpreted?
I wrote the following program:
#include <stdio.h>
#include <stdarg.h>
#include <alloca.h>
void my_func(int count, ...)
{
va_list args;
va_start(args, count);
for(int i = 0; i < count; i++){
int size = va_arg(args, int); // Reading size as an int
char *buffer = (char *)alloca(size); // Allocating stack memory
snprintf(buffer, size, "Hello %d", i);
printf("%s\n", buffer);
}
va_end(args);
}
int main(){
my_func(2, 10, "wrong_type");
return 0;
}
-fsanitize=undefined
show invalid memory access warningCan alloca() cause stack corruption in a variadic function when arguments are mismatched?
The 2nd call to int size = va_arg(args, int);
is the problem.
The following alloca()
is too late to be the problem with OP's code.
Code has trouble with or without alloca()
.
type va_arg(va_list ap, type);
... The parameter type shall be an object type name. If type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases: ... (the listed exceptions do not apply to OP's code).
C23 draft § 7.16.1.1 2
int size = va_arg(args, int);
on the 2nd iteration is undefined behavior (UB). Code has gone off the rails.
After that, alloca()
is simply more train wreck.