Skip to content

Commit 1089f61

Browse files
committed
Fix RandomPCG::random(int, int) overflow bug
- Use int64_t for subtraction before converting to uint32_t - Don't add one to uint32_t max value for rand() bounds
1 parent 6a6a116 commit 1089f61

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

core/math/random_pcg.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,15 @@ int RandomPCG::random(int p_from, int p_to) {
8080
if (p_from == p_to) {
8181
return p_from;
8282
}
83-
return int(rand(uint32_t(Math::abs(p_from - p_to)) + 1U)) + MIN(p_from, p_to);
83+
84+
int64_t min = MIN(p_from, p_to);
85+
int64_t max = MAX(p_from, p_to);
86+
uint32_t diff = static_cast<uint32_t>(max - min);
87+
88+
if (diff == UINT32_MAX) {
89+
// Can't add 1 to max uint32_t value for inclusive range, so call rand without passing bounds.
90+
return static_cast<int64_t>(rand()) + min;
91+
}
92+
93+
return static_cast<int64_t>(rand(diff + 1U)) + min;
8494
}

0 commit comments

Comments
 (0)