Stream: beginners

Topic: taged unions heap allocation


view this post on Zulip Fabian Schmalzried (Jan 15 2023 at 22:14):

Hi everyone, there is a question that popped into my head recently. I'm not sure if the question makes sense, and to what extent it makes any difference at all. I don't know much about low-level stuff so far.
So here's how I understand it: if I have a [Small U8, Large U64], the maximum necessary memory on the stack is allocated for it (because we need to know the size at compile time).
But how does it look when I move it to the heap (Box [Small U8, Large U64]). If there is actually a Small U8 in the box, will there still be room for a U64 on the heap, or actually only for the U8? Or is that even something that the platform can decide?

view this post on Zulip Ayaz Hafiz (Jan 15 2023 at 23:08):

A box allocates on the heap what would otherwise be allocated on the stack - so in this case the memory needed to store a “Large U64” would be allocated on the heap (via roc_alloc) even if you are boxing a “Small U8” variant of the tag

view this post on Zulip Ayaz Hafiz (Jan 15 2023 at 23:10):

One wrinkle here is that boxing calls “roc_alloc”, which a platform can implement as it likes - so you could implement that as malloc, or something generally more efficient like for example an arena allocator. So while a platform can’t control the memory layout of a Boxed value, it can control where in memory it will ultimately end up


Last updated: Jul 06 2025 at 12:14 UTC