5 ms·
Care to share your Vector implementation that is "stack safe" and "UB safe"?
by jjnoakes 2y ago
Care to share your Vector implementation that is "stack safe" and "UB safe"?
- reynmorris 2y agoIt's simple, whether the backing memory is heap or stack, it's bounds checked. And overriding all the operators and only returning safe types prevents many types of undefined behavior. Of course you can fuck with it enough to make it unsafe, but at that point you know exactly what you're doing
- tialaramex 2y agoWithout seeing it, of course it's hard to write examples, but typically for this type of thing it turns out that "fucking with it" enough to be unsafe is easy to do by mistake and so you end up basically saying resorting to classic C++ "Nobody will make mistakes" safety which we know doesn't work. In some cases you can even "fuck with it" less than std::vector and cause memory unsafety because std::vector was implemented by people who've been fucked with before, and this "safe" collection maybe was not. Pushing items from the collection itself into the collection again when it's full is often one way to cause this - the std::vector promises this works correctly.
- reynmorris 2y agoYou can assume that the collection doesn't have good coverage, but what I'm saying is the constructs in the C++ language are there to make it have good coverage. Pair this with some Clang sanitation (like banning raw pointers) and you'd have to go out of your way to make it unsafe.
- School-Cotton 2y agoDoes it stop you from writing code like this? Vector<int> v {1, 2, 3}; int *p = &v[0]; v.push_back(4); printf("%d\n", *p); // this is UB
- reynmorris 2y agoThat is not an issue with the safety of the Vector, it is an issue with the safety of 'int' and raw pointers. If the Vector grows, that pointer points to freed memory. But yes, in my implementation I have a safe version of int called 'i32' which overrides the & operator and doesn't allow it to return raw pointers.
- UncleMeat 2y agoIt absolutely is a concern about vector. Iterator invalidation is a property of a type and its interfaces. One could design a vector implementation that doesn't invalidate pointers and doesn't provide this footgun to users. There are significant costs to this safety, of course, just like adding bounds checks.