I am learning Zig by looking at examples and documentation. In some examples, the initialization of the generic allocator (usually named gpa
) being followed by defer gpa.deinit()
. Removing this will not trigger a compiler error. So, my question is, how do I know when I call a function that returns an object if that allocates memory - and hence I should free that memory myself?
Do I need to look at the source code?
Most code seems to follow this convention:
- If you
init*()
something, you shoulddeinit()
after you are done using it. - If you
alloc()
something, you shouldfree()
it. - If you
create()
something, you shoulddestroy()
it.
I think the GPA is one of the few things that doesn’t quite follow the rules here, but generally if you create an allocator, then you should also clean it up later.
Removing this will not trigger a compiler error.
The reason why it doesn’t trigger a compiler error is because it often enough isn’t a bug. With an ArenaAllocator for example, we don’t need to free/destroy/deinit data created by it.
However the GeneralPurposeAllocator will actually tell you about memory leaks. So if you e.g. call gpa.allocator().alloc(...)
and forget to free it, then the GPA will give you a stacktrace of the memory leak at runtime (in debug mode). However note that the leak checking is only executed inside the gpa.deinit method, so if you forget that, then you are in trouble.
Hello @antonioastorino
Welcome to ziggit
If there is a deinit
you must call it. Currently it depends on the documentation to specify who owns what.
See:
I understand. Thank you for the prompt and clear answer.