4 ms·
I would like Zig to do more to protect users from dangling stack pointers somehow. I am almost entirely done writing such bugs, but I catch them in code review
by anonymoushn 4y ago
I would like Zig to do more to protect users from dangling stack pointers somehow. I am almost entirely done writing such bugs, but I catch them in code review frequently, and I recently moved these lines out of main() into some subroutine:
var fba = std.heap.FixedBufferAllocator.init(slice_for_fba);
gpa = fba.allocator();
slice_for_fba is a heap-allocated byte slice. gpa is a global. fba was local to main(), which coincidentally made it live as long as gpa, but then it was local to some setup subroutine called by main(). gpa contains an internal pointer to fba, so you run into trouble pretty quickly when you try allocating memory using a pointer to whatever is on that part of the stack later, instead of your FixedBufferAllocator.
Many of the dangling stack pointers I've caught in code review don't really look like the above. Instead, they're dangling pointers that are intended to be internal pointers, so they would be avoided if we had non-movable/non-copyable types. I'm not sure such types are worth the trouble otherwise though. Personally, I've just stopped making structs that use internal pointers. In a typical case, instead of having an internal array and a slice into the array, a struct can have an internal heap-allocated slice and another slice into that slice. like I said, I'd like these thorns to be less thorny somehow.
- throwawaymaths 4y agoThis. I believe it is in the works, but postponed to finish up self-hosted. https://github.com/ziglang/zig/issues/2301 https://github.com/ziglang/zig/issues/2301
- 10000truths 4y agoAlternatively, use offset values instead of internal pointers. Now your structs are trivially relocatable, and you can use smaller integer types instead of pointers, which allows you to more easily catch overflow errors.
- anonymoushn 4y agoThis is a good idea, but native support for slices tempts one to stray from the path.
- alphazino 4y ago> so they would be avoided if we had non-movable/non-copyable types. There is a proposal for this that was accepted a while ago[0]. However, the devs have been focused on the self-hosted compiler recently, so they're behind on actually implementing accepted proposals. [0] https://github.com/ziglang/zig/issues/7769 https://github.com/ziglang/zig/issues/7769