Skip to content

Commit

Permalink
Cast to larger type before doing arithmetic to avoid signed integer o…
Browse files Browse the repository at this point in the history
…verflow

https://godbolt.org/z/soTad4zEq

this godbolt links shows that it is UB to multiply then cast if the amount is large enough
  • Loading branch information
ZXShady authored and ChrisThrasher committed Sep 29, 2024
1 parent f297287 commit b626f65
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/CSFML/System/Time.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ sfTime sfSeconds(float amount)
////////////////////////////////////////////////////////////
sfTime sfMilliseconds(int32_t amount)
{
return {static_cast<int64_t>(amount * 1000)};
return {int64_t{amount} * 1000};
}


Expand Down
3 changes: 3 additions & 0 deletions test/System/Time.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,7 @@ TEST_CASE("[System] sfTime")
CHECK(sfSeconds(10).microseconds == 10'000'000);
CHECK(sfMilliseconds(10).microseconds == 10'000);
CHECK(sfMicroseconds(10).microseconds == 10);

CHECK(sfMilliseconds(std::numeric_limits<int32_t>::max()).microseconds == 2'147'483'647'000);
CHECK(sfMicroseconds(std::numeric_limits<int64_t>::max()).microseconds == std::numeric_limits<int64_t>::max());
}

0 comments on commit b626f65

Please sign in to comment.