C++ Logo

std-discussion

Advanced search

Re: Structured dynamic stack allocation

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 14 Jan 2025 14:00:23 -0800
On Tuesday 14 January 2025 13:14:28 Pacific Standard Time Tiago Freire via Std-
Discussion wrote:
> * A facility that tells you how much stack is available and can be used – So
> that you don’t accidentally blow up the stack, and you can make an informed
> decision on either or not you want to allocate something on the stack or
> fallback to using the heap.

This probably requires an operating system change and probably the cooperation
of the low-level C library, for functions like setcontext() and signal
handling on the alternate stack. Given that, I suggest you abandon this
requirement.

> * A facility to resize how much of the stack is reserved – Which would allow
> you to decrease the amount of memory as well as increase it (right now we
> can only increase it with alloca).

That probably won't work or will be implemented as a "no-op". It would be too
complex to deal with a fragmented stack for new allocations to be worth it,
and you can't shrink the stack usage while it's fragmented.

And anyway, what's the point? Shrinkable memory allocations already exist on
the heap and freeing/shrinking memory is incredibly fast. Memory allocation on
the heap is also very fast, if the allocator is using a per-thread arena like
it should. So stack-based allocation should only be used for incredibly simple
allocations that can be very fast and are also not very big. Otherwise, just
use the heap.

> Some constraints seem obvious, like functions that use dynamic stack can not
> be inlined by the compiler otherwise it could be ill formed.

Why not? They just modify the stack frame of the function they've been inlined
into or the compiler restores the stack when the block is done with.



-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel DCAI Platform & System Engineering

Received on 2025-01-14 22:00:32