I wrote a simple code that takes an integer as input from user and allocates an array of that variable size.
#include <stdio.h>
int main(){
int n, i;
scanf("%d", &n);
int arr[n];
for(i=0; i<n; i++){
arr[i] = i;
}
for(i=0; i<n; i++){
printf("%d\t", arr[i]);
}
return 0;
}
The above code works perfectly (if the array size is not very large, give seg fault for size around 2,150,000). How is that even allowed? I thought this should be done using dynamic memory allocation since the array size is variable.
My entire concept of memory allocation has been shaken. Please explain under what conditions is this allowed (should that be a legal code).