Hacker News new | ask | show | jobs
by godshatter 709 days ago
>Which can be an issue if you want to initialize a 2MB large heap-allocated object (e.g. heap-allocating a large nested struct or a big array).

>Without guaranteed “placement new” that can mean that your 2MB object gets constructed on the stack and copied to the heap. And while Linux defaults to a 4MB stack, Windows defaults to 1MB and will crash your program. Or it might work if the compiler optimizes in your favor.

C gets a lot of hate, often for good reasons, but at least you know where your memory is coming from when you are allocating it yourself. If you're allocating a large heap-allocated object, you're grabbing the memory directly from the heap.

1 comments

Memory allocation is one of the areas where currently C/C++ has or had genuine advantages over Rust. Custom allocators took Rust years, and giving standard library constructs like a Vector a custom allocator that isn't the global allocator is still experimental (=opt-in nightly-only). Similarly while Rust gives you good control over where the data ends up being stored, there is no way to make sure it isn't also put on the stack during function execution. One of the implicit assumptions underlying the language seems to be that the stack is cheap and effectively infinite while the heap is expensive. So you have a lot of control over what touches the heap, but less control over what touches the stack.

Those are temporary pains that have remedies in the works. Rust is a fairly young language, and a lot of good-enough solutions get thrown out before ever getting beyond the experimental stage. But if you are writing software today then needing absolute control over where exactly your data touches is a good reason to prefer C/C++ today. Not that that's a very common need.

I'm not persuaded that scribbling on a Box<MaybeUninit<T>> until it's initialised is less ergonomic than the C. Which isn't to say it's a desirable end state, I just don't see C as a more ergonomic alternative even for this application.