Skip to content

Commit

Permalink
Convert to unsigned char before invoking std::isprint().
Browse files Browse the repository at this point in the history
As the documentation states, the caller must check that the input
character in [`std::isprint()`](https://en.cppreference.com/w/cpp/string/byte/isprint) is a valid `unsigned char`:

> Like all other functions from `<cctype>`, the behavior of
> `std::isprint` is undefined if the argument's value is neither
> representable as `unsigned char` nor equal to `EOF`. To use these
> functions safely with plain `char`s (or `signed char`s), the argument
> should first be converted to `unsigned char`:
>
> ```cpp
> bool my_isprint(char ch)
> {
>     return std::isprint(static_cast<unsigned char>(ch));
> }
> ```

The aforementioned undefined behavior manifests as a debug assertion
when compiled with MSVC:

![image](https://github.com/user-attachments/assets/144e3573-f53c-4e89-a0cd-d615caa2749e)

The affected functionality was introduced in #122.

Fixes #173.
  • Loading branch information
cristian64 authored and dreamsyntax committed Aug 18, 2024
1 parent 9aa9b27 commit bcb146f
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Source/Common/MemoryCommon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ std::string formatMemoryToString(const char* memory, const MemType type, const s
if (c == '\0')
break;

if (std::isprint(c))
if (std::isprint(static_cast<int>(static_cast<unsigned char>(c))))
{
text.push_back(c);
}
Expand Down
2 changes: 1 addition & 1 deletion Source/GUI/MainWindow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ void MainWindow::updateStatusBar()
{
for (char& c : gameID)
{
if (!std::isprint(c))
if (!std::isprint(static_cast<int>(static_cast<unsigned char>(c))))
{
c = '?';
}
Expand Down

0 comments on commit bcb146f

Please sign in to comment.