3 ms·
> I don't think I understand what is meant by "type confusion". Accessing a memory location with one type as if it's another. In C or C++ it's usually because
by jamii 6y ago
> I don't think I understand what is meant by "type confusion".
Accessing a memory location with one type as if it's another. In C or C++ it's usually because you accessed a union without checking a tag somewhere else.
One classic way this happens is in an interpreter where you have a big enum for all the different possible data types:
https://github.com/MaterializeInc/materialize/blob/1b9b3cfab699d2df18dcfa17a0880e88bb39b187/src/repr/src/scalar.rs#L28 https://github.com/MaterializeInc/materialize/blob/1b9b3cfab...
And then in various builtin functions you expect particular types:
https://github.com/MaterializeInc/materialize/blob/main/src/expr/src/scalar/func.rs#L758-L760 https://github.com/MaterializeInc/materialize/blob/main/src/...
In rust and zig this code will produce a runtime error if you screw up, but in c it's easy to forget to check the tag and then you get UB. Similarly unwrap is checked in rust and zig but the equivalent in c - dereferencing a pointer that you are pretty sure is not null - is not.
Of course rust and zig both have support for c-style unions too, but they're not the first thing people reach for.
- quietbritishjim 6y agoThanks for answering. As I said in another comment (in reply to another tsimionescu who suspected that's what you meant), I maintain that this is a compile time error. Yes, one usage is to panic if the contents of the enum is not what you expect, in which case an unexpected type causes a runtime error. But that is the programmer choosing to deal with it way. Fundamentally in the language, mismatching type is a compile time error. In many situations it's feasible to exhaustively match and deal with all possible cases of an enum (which then causes a compile time error if you try to reference one of the other inner types from within the "wrong" case). Where one particular case is expected, you can often ensure through the type system that this case is the only possibility by using that individual type directly rather than passing that enum around. In some situations its not feasible or it is feasible but the extra faff isn't worth the reward - but even then I don't think it justifies saying that the type confusion is detected in runtime in a comparison of languages.
- tsimionescu 6y ago> In rust and zig this code will produce a runtime error if you screw up, but in c it's easy to forget to check the tag and then you get UB. As pointed out elsewhere, somewhat surprisingly, this is not UB in C, though it is in C++. In C it is merely unspecified behavior, but perfectly safe if intended.
- jamii 6y agoMy bad, should have verified first.