C++ Logo

std-proposals

Advanced search

Re: [std-proposals] C++ never had a compiler without a stack

From: David Brown <david_at_[hidden]>
Date: Tue, 15 Aug 2023 17:30:09 +0200
On 15/08/2023 16:17, Thiago Macieira via Std-Proposals wrote:
> On Tuesday, 15 August 2023 06:56:20 PDT Julien Villemure-Fréchette via Std-
> Proposals wrote:
>> I think the intent of alloca in Posix and VLA in C was specifically to have
>> automatic cleanup semantics for objects with block scoped lifetime. C++
>> already has the language feature that makes it possible to ensure proper
>> cleanup at end of scope, so the need for VLA evaporates. If you look
>> closely, the C language doesn't seem to make any mention of the stack in
>> the specification of VLAs, I think a pair of malloc/free may be a possible
>> implementation.
>
> The difference is that alloca() has determinstic runtime (provided it doesn't
> overflow), wheras malloc() cannot be guaranteed to.
>

That is one difference, yes. The other key difference is that that run
time is absolutely minimal - typical "alloca()" calls simply add (or
subtract) a value to a stack pointer register, which is vastly faster
than a call to malloc() could ever be. (For real-time systems,
"deterministic" is more important than "fast". But it's nice to be fast
too!)

VLA's are often an alternative to alloca() in C, but there are
differences in the semantics - VLA's are deallocated at the end of the
scope, while alloca() space is deallocated at the end of the function.

And C++ has no VLA's or any equivalent, so if you want fast, small local
allocations, you need to use alloca() in C++.

Received on 2023-08-15 15:30:18