Fun with recursions
Steven Schveighoffer
schveiguy at gmail.com
Sat Feb 22 16:38:08 UTC 2020
On 2/22/20 4:59 AM, Andrej Mitrovic wrote:
> On Friday, 21 February 2020 at 17:52:01 UTC, Steven Schveighoffer wrote:
>> https://gist.github.com/schveiguy/962e36cea6a979a47b708cb4335f9f82
>
> Well, I don't like the 'new' call there. :)
You know Generator is a Fiber/class and it allocates stack, right? Or is
it just a problem with the GC running?
I also just noticed, this is potentially going to return a reference to
stack space that goes out of scope (you are avoiding new at the cost of
memory safety here). Even if you postblit the class pointer to the right
place, the compiler is free to move your struct around. You really
should allocate this on the heap.
https://gist.github.com/AndrejMitrovic/282d062c09a6df697476a8304bb23c19#file-get_recursive-d-L54
Not only that, but your destructor doesn't destroy the fiber, so you are
leaking stack memory.
Any way you want to allocate stack, you can potentially use the gist I
posted. The linked list is the easiest to do, but you could also do a
amortized constant allocation scheme based on an array if you wanted.
You can even use C malloc if you don't care about dangling pointers to
range elements. Or use RefCounted to allocate the linked list.
-Steve
More information about the Digitalmars-d
mailing list