I wrote a C program that accepts integer input from the user, that is used as the size of an integer array, and using that value it declares an array of given size, and I am confirming it by checking the size of the array.
int main(int argc, char const *argv)
This is not a "static memory allocation". Your array
k is a Variable Length Array (VLA), which means that memory for this array is allocated at run time. The size will be determined by the run-time value of
The language specification does not dictate any specific allocation mechanism, but in a typical implementation your
k will usually end up being a simple
int * pointer with actual memory block being allocated on the stack at run time.
For a VLA
sizeof operator is evaluated at run-time as well, which is why you obtain a correct value from it in your experiment. Just prefer to use
%ld) to print values of type
The primary purpose of
malloc (and other dynamic memory allocation functions) is to override the scope-based lifetime rules, which apply to local objects. I.e. memory allocated with
malloc remains allocated "forever", or until you explicitly deallocate it with
free. Memory allocated with
malloc does not get automatically deallocated at the end of the block.
VLA, as in your example, does not provide this "scope-defeating" functionality. Your array
k still obeys regular scope-based lifetime rules: its lifetime ends at the end of the block. For this reason, in general case VLA cannot possibly replace
malloc and other dynamic memory allocation functions.
But in specific cases when you don't need to "defeat scope" and just use
malloc to allocate a run-time sized array, VLA might indeed be seen as a replacement for
malloc. Just keep in mind, again, that VLA are typically allocated on the stack and allocating large chunks or memory on the stack to this day remains a rather questionable programming practice.