5 ms·
I actually feel that C++ memory management is less safe than that of C, because smart pointers provide the same opportunity for use-after-free while being much
by pcwalton 9y ago
I actually feel that C++ memory management is less safe than that of C, because smart pointers provide the same opportunity for use-after-free while being much more opaque about when the destruction occurs. The rules about when destructors of temporaries are called in the evaluation of expressions are subtle.
- blub 9y agoI'd be happy to discuss an example, because right now the idea that smart pointers are opaque about destruction is unfortunately too abstract for me to give a helpful reply to.
- pcwalton 9y agoConsider situations like this: https://stackoverflow.com/questions/17362673/temporary-lifetime-extension https://stackoverflow.com/questions/17362673/temporary-lifet... It's undefined behavior, despite not calling free anywhere. Replace with std::string and it could be use after free. In C, UAF wouldn't happen that silently for heap memory.
- blub 9y agoA similar example was posted by matthieu_m on Reddit a while back, but that's still not worse than C, even if it's an unfortunate gap in compiler diagnostics. From my POV compilers should warn that this code is potentially dangerous. My rule is: never return a reference or pointer from a function to something whose lifetime you don't have control of.
- pcwalton 9y agoIt's worse than C because you can't have UAF in C without explicitly calling free (or a function that transitively calls free). In C++ freeing is implicit.
- nine_k 9y agoDo you even explicitly free() a RAII-managed pointer? If yes, why?
- pcwalton 9y agoNo, and that's the problem. Free can effectively be called invisibly, causing UAF.