Home > Enterprise >  Xcode puts C VLAs on the stack and not on the heap
Xcode puts C VLAs on the stack and not on the heap

Time:09-21

Xcode puts C variable-length arrays on the stack and not on the heap.

Is this correct? If yes, considering VLAs should let developer avoid malloc-free calls, why Xcode does it?

CodePudding user response:

Using the stack is the natural way to implement variable-length arrays and any other object with automatic storage duration because:

  • The stack is designed for last-in-first-out memory use: The data for a function (or a nested block) is pushed onto the stack when the function starts, and it is removed from the stack when execution of the function ends.
  • Allocation and release are easy. Each is achieved just by adjusting the stack pointer, and it can be easily adjusted by the size needed for a variable-length array.

Implementing them with allocation from the same pool used for malloc would be a problem because a function is not always terminated by returning. C has setjmp and longjmp features that allow jumping directly to an earlier point in the call stack. longjmp can be implemented mostly by setting the stack pointer and program counter to the values they had when the setjmp was performed, and those values are stored in the setjmp context object. If variable-length arrays were allocated from the malloc pool, it would be necessary to go through all the levels of the call tree on the stack, find the variable-length arrays that were allocated in each, and free them. And that means it would also be necessary to create records of those allocations in the stack tree as they are made.

  • Related