The malloc function always allocate memory on the heap. However, while studying the Escape Analylis Article on Wikipedia, I came to know that as an optimization, a compiler can convert heap allocations to stack allocations. For example, if it sees that an allocated memory is only used and then freed inside a function.
Now my question is, is there a way that the programmer can do so himself. That is allocate memory on stack? I know C99 allows a variable to be given as size for an array declaration, but say the programmer wants to resize it. Can it be done?
alloca()is what you’re looking for. Of course, if you know your structures dimensions statically, it’d be better to use local variables instead.