4 ms·
The first version I implemented did allocate and return the allocated output buffer, but I scrapped that design I never changed the return value after I did th
by henesy 5y ago
The first version I implemented did allocate and return the allocated output buffer, but I scrapped that design
I never changed the return value after I did this and didn’t see an issue at the time
For the record, this program was written casually on a live stream and is hardly a textbook definition of correctness :)
- e12e 5y agoOk, thank you. I didn't mean it as criticism, just genuinely curious about the (c language) idioms involved - especially after struggling a bit with Zig strings in relation to advent of code - and after seeing the approach rust takes on ownership. 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.
- henesy 5y agoThe other comments are correct that there's value in returning a value even if it was passed in to make chaining functional calls easier. 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);