Skip to content

Commit

Permalink
Fix RandomPCG::random(int, int) overflow bug
Browse files Browse the repository at this point in the history
- Use int64_t for subtraction before converting to uint32_t
- Don't add one to uint32_t max value for rand() bounds
  • Loading branch information
aaronp64 committed Dec 5, 2024
1 parent 1f47e4c commit 1de50ce
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion core/math/random_pcg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,15 @@ int RandomPCG::random(int p_from, int p_to) {
if (p_from == p_to) {
return p_from;
}
return rand(abs(p_from - p_to) + 1) + MIN(p_from, p_to);

int64_t min = MIN(p_from, p_to);
int64_t max = MAX(p_from, p_to);
uint32_t diff = static_cast<uint32_t>(max - min);

if (diff == UINT32_MAX) {
// Can't add 1 to max uint32_t value for inclusive range, so call rand without passing bounds.
return rand() + min;
}

return rand(diff + 1) + min;
}

0 comments on commit 1de50ce

Please sign in to comment.