3 ms·
> Some languages do that for you. Allocating on the stack by default and falling back to the heap when it wouldn't be safe to allocate on the stack. e.g. if the
by burntsushi 13y ago
> Some languages do that for you. Allocating on the stack by default and falling back to the heap when it wouldn't be safe to allocate on the stack. e.g. if the object can outlive the current function call, it shouldn't be allocated on the stack.
> If the Rust compiled doesn't known how to spot unsafe stack allocations, then you don't have memory safety.
This seems like a weird thing to say given that the Rust compiler does fairly sophisticated analysis on the lifetime of data. (And yes, Rust has memory safety.)
As a low level language, the programmer decides explicitly what is allocated on the stack and what is on the heap.
- fooyc 13y agoIs there many cases where it's safe to allocate an object on the stack, but you would want to allocate it on the heap instead ? (Appart from the the object being too big.)
- burntsushi 13y agoAs I said, it's about making costs explicit. Otherwise, you're relying on the compiler's escape analysis to choose whether to allocate something on the heap or the stack. A programmer might not realize that something escapes, and thus, there is a heap allocation that the programmer thought was a stack allocation. It's worth something to be able to say, "put this on the stack dammit" and if it can't go on the stack safely, require that the compiler yell at you.