Finding bugs on tagged unions mismatches
Unions in C may have several data members, but all of them start at the same memory address. In essence, unions store a single value with multiple type alternatives, with the current type of the value being the active type. However, plain unions do not keep track of the active type, and reading the value with an incorrect type might be undefined behaviour in C, and definitely undefined in C++. For this reason, programmers often resort to using tagged unions, where an enumerating variable is used alongside the union – the value of the enumerating variable keeps track of the active type in the union.While this makes accessing the value inside a union safer, it is still possible to make mistakes with tagged unions. During code maintenance, the number of data members of a union might change, and the number of constants declared in the enumeration needs to be in sync. If these values are not equal, its a sign of code smell.In this paper, we investige how programmers use and misuse of tagged unions. We implemented a static analysis check in Clang- Tidy, a subproject of LLVM, which has since been accepted into the project by the community and will be available for every Clang-Tidy user starting from the next major Clang release v20.0.0 [1]. We ran our check on large, open source C and C++ projects, and were able to specify a new reliable rule for the usage and maintenance of tagged unions.
Authors
- Zoltán Porkoláb (ORCID: https://orcid.org/0000-0001-6819-0224)
- Kristóf Umann (ORCID: https://orcid.org/0000-0002-6679-5614)
- Gábor Tóthvári
Publication Details
- Published
- 2024-11-13
- DOI
- https://doi.org/10.1109/informatics62280.2024.10900816
- Primary Topic
- Logic, programming, and type systems
- Type
- article
- Field-Weighted Citation Impact
- 0.00
Funders
- Innovation Fund