After removing all the calls to malloc and calloc from our code for an embedded system, I was surprised to find that malloc was still being linked in. The call graph pointed me to a function which had no explicit *alloc calls, and no calls to any library functions that might allocate, like strdup
.
I had to look at the generated assembly to realize that it was due to an inlined function which contained a VLA.
I thought VLAs had to be stack-allocated. Is this compiler broken?
There is no requirement that VLAs be allocated from the stack (the language standard doesn't even mention stacks or heaps). The only requirement is as follows:
Given this, it makes sense to allocate from the stack, but for very large objects this may not be possible, and such an object may be allocated from the heap or some other memory segment instead. The bookkeeping is up to the implementation.
No, they don't have to be stack-allocated. I would use
alloca
if you want it to be on the stack.Source 1: https://stackoverflow.com/a/2035292/283342
Source 2: https://en.wikipedia.org/wiki/Variable-length_array