4 ms·
Is allocating without a subsequent `defer` a warning?
by davikr 3y ago
Is allocating without a subsequent `defer` a warning?
- flohofwoe 3y agoHow would you handle the valid case that a function returns a pointer to heap allocated memory? "Manual memory management" is exactly what the label says, it's "manual". What you usually do is group all allocated items with the same max lifetime in an arena allocator created somewhere up the call stack, and then defer-free the entire arena instead of each individual item. In real world code there's hardly a situation where each item requires its own lifetime tracking, instead they are usually lumped together with other items of a similar lifetime. Zig's GeneralPurposeAllocator also helps to catch typical memory-related issues at runtime (like leaks and dangling access), e.g. see: https://github.com/ziglang/zig/blob/master/lib/std/heap/general_purpose_allocator.zig https://github.com/ziglang/zig/blob/master/lib/std/heap/gene... Tagged-index-handles are also always an option to achieve spatial and temporal runtime memory safety at a higher level: https://floooh.github.io/2018/06/17/handles-vs-pointers.html https://floooh.github.io/2018/06/17/handles-vs-pointers.html
- fatihpense 3y agoYes, another valid case is passing heap-allocated pointers between WASM guest and host. I have an example here if anyone is interested: https://github.com/fatihpense/zig-wasm-string-and-struct https://github.com/fatihpense/zig-wasm-string-and-struct As a newbie in low-level programming, being able to return "heap-allocated pointer" instead of "stack-allocated pointer to a struct in heap" was a challenge at first :) But I love how everything is explicit in Zig.
- fatihpense 3y agoFrom my experience, It catches memory errors in test blocks. Here is more information: https://ziglang.org/documentation/master/#Report-Memory-Leaks https://ziglang.org/documentation/master/#Report-Memory-Leak...