dynamically allocating on the stack

Dmitry Olshansky dmitry.olsh at gmail.com
Sat Apr 21 18:52:45 UTC 2018


On Saturday, 21 April 2018 at 13:30:55 UTC, Cym13 wrote:
> On Saturday, 21 April 2018 at 12:08:09 UTC, Dmitry Olshansky 
> wrote:
>> On Saturday, 21 April 2018 at 07:37:50 UTC, Mike Franklin 
>> wrote:
>>> Does D have some way to dynamically allocate on the stack?  
>>> I'm looking for something roughly equivalent to the following 
>>> C code.
>>>
>>> int doSomething(size_t len)
>>> {
>>>     char stackBuffer[len + 1];
>>>     doSomethingElse(stackBuffer);
>>> }
>>>
>>
>> Unbounded allocation on stack is kind of anti-pattern and a 
>> potential DoS vector.
>
> I'm having trouble seeing how unbounded heap allocations aren't 
> equally a potential DoS vector.

I could see what you meant, but really stack is typically far 
more limited then heap in size.

Unless you tune the stack size yourself (i.e. you both build an 
app and control the environment) there is no sensible way to know 
the size you can use. It’s also heavily platform dependent.

With heap it’s usually far less limited resource.

Lastly Fibers usually have small stacks.

>
>> A separate region allocator is exactly as fast and can easily 
>> survive across boundaries of function calls.
>
> I guess if OP wants it on the stack it's because it doesn't 
> need to survive across boundaries of function calls so this 
> buys nothing in this case.

Yet nothing to lose and much safer bet in general.

In general, I’d expect performance to be the goal here. If so 
then zone/region allocation is a well known pattern that is not 
restricted to individual arrays and is widely used in games and 
industry-grade stuff like browsers/VMs.

>
>> Also you probably want something like char[X] = void;
>>  for efficiency if allocating on stack.
>>
>>> Thanks,
>>> Mike




More information about the Digitalmars-d-learn mailing list