Search code examples
cdeclare

Why do we not declare arrays with variable size?


My supervisor saw something in my C code similar to:

size = f(some parameters);
int array[size];

He said that it is preferable to allocate such arrays with malloc. His description was something like:

Allocating it on the stack like that requires that your stack remains valid for the entire run-time of the program.

I had no clue what he meant, so this is just as close as I remember to his wording by the end of the meeting, without knowing the actual meaning. What did he mean? (alternatively, maybe someone can explain another reason not to declare arrays in such manner).


Solution

  • Any variable declared local will be only valid during the execution of the function, as it will be allocated in stack

    If you need this array outside the function where it was declared you need to allocate it with malloc, but if you are using it only inside this function and during this execution is okay

    Just mind that any local variables will use stack memory, so be sure that your array will never be big enough to cause a stack overflow in your program!