Issue Details
- Number
- 19496
- Title
- Use of C++ undefined behavior in various `IteratorComparators`
- Description
- **Expected behavior**
All C++ code to be 100% using legal C++ and not UB which can lead to subtle bugs if not now, then perhaps in the future.
**Actual behavior**
Use of undefined behavior in at least two places:
- https://github.com/bitcoin/bitcoin/blob/42fe6aad326f62c7e6ea12ee873149257f67ce5d/src/net_processing.cpp#L227
- https://github.com/bitcoin/bitcoin/blob/42fe6aad326f62c7e6ea12ee873149257f67ce5d/src/miner.h#L67
**Background**
Please see this part of the C++ specification: https://en.cppreference.com/w/cpp/language/operator_comparison
In particular I will quote the relevant section here:
> If two pointers are not specified to compare greater or compare equal, the result of the comparison is unspecified. The result may be nondeterministic, and need not be consistent even for multiple evaluations of the same expression with the same operands in the same execution of the program:
```c++
int x, y;
bool f(int* p, int* q) { return p < q; }
assert(f(&x, &y) == f(&x, &y)); // may fire in a conforming implementation
```
Note that in the above-linked section (which I admit is difficult to decipher) -- pointers are only specified to have a legal `<` or `>` comparison operations if the objects they point to either belong to the same array, or if the objects they point to live basically as members in the same object (i.e. as class members). *This is unlike in C*. The code will compile.. it will run -- but like the above section states, and the above sample program illustrates -- the results may be non-deterministic!
In practice it appears the code works in bitcoin for all known compilers and platforms -- but is not guaranteed to do so forever and may lead to subtle bugs in the future as compilers evolve or as `libstdc++` evolves.
- URL
-
https://github.com/bitcoin/bitcoin/issue/19496
- Closed by
-
Back to List