by e12e · 4y ago · 0 comments
In zig the idiomatic approach (as far as I can tell) is to manage allocator in main/the caller, and passing that down to the callee. Thus allocation strategy (heap/stack/arena etc) is global/caller determined, while resources are "locally" managed.
I generally work in high level languages like ruby, where one rarely worries about the details of (especially string) allocation (beyond trying to not create way too many copies/buffers).
So it's interesting to see what kind of balance on encapsulation/delegation of this concern can/should be found in C.
Thank you for taking the time to comment.
This can get a little tricky when ownership comes in to play since you don't want to end up in a situation where (not in the above program's situation, but in general) the caller might pass out a value that never gets freed and you can easily create memory leaks.
You wouldn't want to do, for example:
print("%s\n", smprint("%s", L"世界"));
Since smprint(2)'s return value was allocated and will need to be freed, but we have no way of doing that after the value is passed.You'd need to do:
char *buf = smprint("%s", L"世界");
print("%s\n", buf);
free(buf);