3 ms·
> Unique pointers provide no protection against use after free, because you can take a reference to their contents and that reference can become dangling. Yes,
by nly 9y ago
> Unique pointers provide no protection against use after free, because you can take a reference to their contents and that reference can become dangling.
Yes, it's possible, however references should only ever have local scope so, unless you're dealing with threads or asynchrony it's hard to write sane code where this happens, and if you have those things, and you're passing refs or ptrs, then I don't have to tell you that things are bad.
> as opposed to in C where an explicit call to free is required, this makes C++ more prone to UAF than C.
I don't see this. C++ destructors run after the last line of your code block, if something uses a destructed object then it can only be because you passed a pointer or reference to it to something else that wasn't yet destroyed.
Mentioning free() just implies that you're willing to accept resource leaks to avoid UAF bugs, which is nuts because UAFs can be a lot easier to debug.
- cesarb 9y ago> Mentioning free() just implies that you're willing to accept resource leaks to avoid UAF bugs, which is nuts because UAFs can be a lot easier to debug. If you're focused on security, it goes in the opposite direction: a resource leak can lead to a denial of service, but an use-after-free can lead to remote code execution, which is much worse. From that point of view, it's worth it risking a resource leak if by doing that you prevented a potential instance of remote code execution. By the way, > C++ destructors run after the last line of your code block Aren't there many situations where the C++ destructor runs at the end of the current statement? IIRC, if you call a function which returns a temporary, then call a method on that temporary which returns a reference to within the temporary, and assign the result to a variable, all in a single statement, the temporary will be destructed while the reference to its contents is still live.
- nly 9y ago> then call a method on that temporary which returns a reference to within the temporary The obvious answer to this would be never to return references to members (or anything tied to the objects lifefime), but if you really must then you can always use a qualifier to prevent this pattern from compiling. https://ideone.com/UuZYJe https://ideone.com/UuZYJe