4 ms·
Well, yes. It's 1970s C technology. There are several options. They all suck. - Pass in a buffer to be filled by the API. The API can't check the buffer size
by Animats 4y ago
Well, yes. It's 1970s C technology.
There are several options. They all suck.
- Pass in a buffer to be filled by the API. The API can't check the buffer size you gave it. Be mentioned in a CERT security advisory for creating a buffer overflow vulnerability.
- Have the API give you a buffer. Reboot your system regularly to recover the memory leaks.
- Free the buffer before returning it, so the caller is using the buffer after free. Debug memory corruption bugs when someone uses an allocator which overwrites freed buffers.
This is what move semantics are for. You call something, it gives you a thing, and now it's yours to use and release. Needs language support to work well, but is the right answer.
- Sharlin 4y agoThere’s another way: pass a pointer to the cleanup function as an out parameter – if it’s a struct you’re returning, just return the pointer as one of the struct fields. This is, of course, how "OO" as in methods and polymorphism is sometimes simulated in C. This way you don’t need to pollute your API with a zillion different `free_foo` functions.
- HarHarVeryFunny 4y agoJust one minor quibble: I'd say it's C++'s classes (not move semantics) that made doing things like this much cleaner - mostly by having a destructor that let's data structures automatically clean up after themselves (release memory) when they go out of scope. Now the developer doesn't need to know or care about whether the structure they were given has internal dynamically allocated components or not. Move semantics is "just" an optimization that makes passing data-owning classes around more efficient. Pre C++11 you'd just return the class by reference to avoid the inefficiency of return by value, but with move semantics you can treat complex types the same as simple ones, and not worry about the efficiency of how you pass them around.
- Veliladon 4y ago> This is what move semantics are for. You call something, it gives you a thing, and now it's yours to use and release. Needs language support to work well, but is the right answer. Isn't this literally Rust?
- woodruffw 4y agoI don't believe this should be downvoted, since it's an earnest question. The answer is that Rust has affine types, which is a fancy way of saying that variables are owned exactly once. The borrow checker enforces this property, essentially by making temporary reference copies of the owned object and proving that they never outlive their backing value. Move semantics are an implementation detail of affine typing, but can also be used (and are successfully applied) outside of purely affine languages like Rust. C++ is probably the most famous example of that, where `std::move` essentially means "extend the lifetime of this value by moving its contents to the lvalue."