Created
October 15, 2025 05:08
-
-
Save Numeez/606b75bfc5a1c6d9a79e20950f3354a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fn decCountInc(self: ?*SnekObject, allocator: std.mem.Allocator) void { | |
| if (self == null) { | |
| return; | |
| } | |
| self.?.referenceCount -= 1; | |
| if (self.?.referenceCount == 0) { | |
| SnekObject.refCountFree(self.?, allocator); | |
| } | |
| } | |
| test "testing decrement ref count" { | |
| const allocator = std.testing.allocator; | |
| const x = SnekObject.newSnekInteger(allocator, 1); | |
| try expect(x.?.referenceCount == 1); | |
| SnekObject.refCountInc(x); | |
| SnekObject.decCountInc(x, allocator); | |
| try expect(x.?.referenceCount == 1); | |
| SnekObject.decCountInc(x, allocator); | |
| // If I call this multiple times after this like this | |
| SnekObject.decCountInc(x, allocator); | |
| SnekObject.decCountInc(x, allocator); | |
| // This will result in Segfault | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usually you think about ownership of which part of the code handles the resource allocation, moves ownership and then the owner has to handle free.
With implementing a garbage collection and reference counting that’s the difficult part as there’s no clear owner of the object being passed around freely.
Not sure how I would implement a check if it’s freed or not. I think you could just free only when you decrement from 1 to 0, but remember to always add 1 when using the object and remove 1 when you’re done.
The function doing the allocation will move ownership to the caller hence it should pre-increment 1 (that way you can check it’s not zero which is not freed yet)