Nondeterministic code is hard to debug since bugs are not consistently reproducible. It’s easy to notice that the code is perhaps nondeterministic if multi-threading or random functions are involved. However we can still write nondeterministic single-threaded code without using random functions.
Random Address
Address space layout randomization randomly arranges the address space positions of stack and heap of a process, which means the address of a variable changes for each run. This is the source of nondeterminism if we try to iterate through an unordered container of pointers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
1 2 3 4 5 6 7 8 9 |
|
As we can see, the address of variable a, b and c keeps changing for each run, which affects their positions in the hash set and, as a result, we will iterate them in different orders.
Lets try to disable ASLR and verify that the nondeterminism is gone:
1 2 3 4 5 6 7 8 9 |
|
Since the nondeterminism is generally undesired, clang has a checker to detect such usages.