#memory safety:

1 messages · Page 1 of 1 (latest)

peak bolt
#

hey guys, a quick question, how is zig better than c in memory safety?

mortal magnet
#

I would not say, that Zig is safer in memory safety, but Zig makes it easier to do the right thing compared to c in memory safety

marble relic
#

Zig, along with most modern takes on low level languages, do improve the memory safety compared to C by adding the most basic of features that help with practical issues you encounter when programming.
That being: slices; bounds-checking.

#

In Zig specifically, those bounds checks only exist when you're NOT using ReleaseSmall or ReleaseFast build modes, but it is otherwise there.

#

Zig also puts checked panics in where there's UB, rather than just making it a hidden codegen thing like it is in C.

peak bolt
#

I see

quick crescent
#

Also, pointers in zig are not optional or nullable by default and you need to specify that they are by putting a ? before the pointer type:

*SomeType vs ?*SomeType

If pointer is not nullable, then you cannot assign a null value to it and the compiler will give an error if you try.

If the pointer is nullable then you need to check if it's not null before you try to use it which prevents null pointer dereferences

Of course you can still have a pointer to an object which doesn't exist anymore if it was invalidated somewhere else in the code, so you still need to be careful with using pointers

#

Zig helps with other memory related bugs like use after free and memory leaks. If a resource gets leaked in a test block, that test will fail and report the leak back to the user

gentle yarrow
#

I will add, the whole idea of allocators for memory management. It has many benefits which is talked about all over through any amount of research in the language. The std.heap.GeneralPurposeAllocator has various verbosity and safety flags, and when compiled in Debug mode, detects memory leaks, double frees, (and bounds checks?) with helpful traces to where in your code they occur. It's quite impressive. On top of that, depending on what you're doing, you can just use an arena allocator for an entire simple tool and it's a lot like fire an forget with a garbage collector. Allocators mean there isn't some global memory malloc function, you pass them around as an allocator in your function parameters, making memory allocations transparent in the signature of the function. This is hidden slightly with managed variations of the data structures in std, but there are unmanaged variations of almost all of them and if you use those your entire program really does have zero hidden allocations.