Based on a comment of someone in another thread:
VLAs introduce more problems than they solve, because you never know if the declaration is going to crash for x being too large for the stack.
This code will overflow because sizeof(a)
is too long for the stack:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n = 100000000;
int a[4][n];
printf("%zu\n", sizeof(a));
return 0;
}
But this one can not because sizeof(a)
is 8 (the size of a pointer in my computer):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n = 100000000;
int (*a)[n];
printf("%zu\n", sizeof(a));
a = malloc(sizeof(*a) * 4);
free(a);
return 0;
}
Is my assumption correct?
Can we determine if the use of a VLA is dangerous or not (may overflow) based on the sizeof
the object?