-
Notifications
You must be signed in to change notification settings - Fork 132
Description
This is an amazing guide. Thanks for writing and sharing. I have some comments on the section 1.9 about "Safety in Zig".
defer allows you to keep free operations physically close to allocations. This helps you to avoid memory leaks, “use after free”, and also “double-free” problems.
defer definitely helps with avoiding memory leaks, but I don't think it helps avoiding use-after-free errors, which are caused by the freed memory still being referenced somewhere else in the program.
pointers and objects are non-nullable by default. This helps you to avoid memory problems that might arise from de-referencing null pointers.
Pointers being non-nullable by default is great. But dereferencing a null pointer is a correctness issue, not a safety issue, at least on all modern systems with a MMU where the address zero is not mapped and dereferencing it will trigger a page fault. It's similar a division by zero. But perhaps I'm missing something or not using the correct terminology.
In contrast, the Zig language is not a memory safe language by default. There are some memory safety features that you get for free in Zig, especially in arrays and pointer objects.
Zig provides spatial memory safety (bound checks), but no temporal memory safety (no reference counting, GC or borrow checker). Carbon has a nice page defining these notions: https://docs.carbon-lang.dev/docs/design/safety/terminology.html.