by rnikander · 4y ago · 0 comments
In Swift (and Kotlin and others) the compiler can prove that you never get a null pointer error at runtime. If you want something that can be null, the type is `T?` (short for `Optional<T>`) instead of `T`. Then there are various syntactically convenient ways of unwrapping it and dealing with the null case. Eg `foo ?? bar` means give me `foo` if it's not null, otherwise `bar`. Or `foo?.x` means: get the property x of foo, if foo is not null.
I haven't used C++ much in recent years. If there's an equivalent, I'd love to know about it.
E.g. in
std::string str;
str is never null, and always a valid object, because it's a value, not a pointer like in most GC'ed or dynamic languagesstd::string str1{"Apple"}; std::string str2 = std::move(str1);
Isn't str1 in an invalid (err, unspecified?) state and you shouldn't use it? It's not `null` sure, but it's not good to use.
It might not be null, but I can't do much more with it than I can with null. I need to assign something new first
What's better is that sanitizers don't detect this form of undefined behavior! (Clean on memory,address,undefined.)
https://godbolt.org/z/7jsxnMs8E
also relevant: https://i.imgur.com/3wlxtI0.gifv
Also, uninitialized by itself does not mean invalid though ? For your example, I wonder if it would make sense to flag it: printf could be implemented in assembly or Fortran for what we know (a few popular libc implementations are done in c++ for instance), and as such I don't know how much sense it would make for its internal usage of the pointed value to be checked against the c++ rules. I'd assume the outcome would be different with std::format or std::cout for instance
I suppose a definition of valid that prohibited uninitialized members would preclude lots of useful stuff like container and buffer types.
From the msan documentation [1], the flaw with my earlier example is that `printf` isn't instrumented.
And to address your other question, I don't know if msan can instrument a function implemented in assembly. It definitely can't deal with something it didn't compile as the instrumentation is added during compilation.
It seems that on godbolt the platform library also isn't instrumented because the equivalent iostream code is msan clean [2]. I suppose that makes sense as it's allowing you to pass arbitrary options to the compiler.
In summary, msan can detect these uninitialized reads but it requires quite a lot of fiddling.
[1]: https://clang.llvm.org/docs/MemorySanitizer.html#handling-ex... [2]: https://godbolt.org/z/Gsxsfn9GT
In Swift you are not allowed to declare a variable without assigning some value or nil to it before the current scope ends.
The semantics of c++ object initialization are such that a constructor will always be called.