Skip to content

Commit

Permalink
Fix undefined behaviour with std::transform and tolower/toupper. (#2795)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chaosvex authored Oct 10, 2024
1 parent f93cab1 commit 061b1ef
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
11 changes: 9 additions & 2 deletions dep/src/g3dlite/stringutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "G3D/stringutils.h"
#include "G3D/BinaryInput.h"
#include <algorithm>
#include <cctype>

#ifdef _MSC_VER
extern "C" {
Expand Down Expand Up @@ -215,14 +216,20 @@ int stringPtrCompare(

std::string toUpper(const std::string& x) {
std::string result = x;
std::transform(result.begin(), result.end(), result.begin(), toupper);
std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c)
{
return std::toupper(c);
});
return result;
}


std::string toLower(const std::string& x) {
std::string result = x;
std::transform(result.begin(), result.end(), result.begin(), tolower);
std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c)
{
return std::tolower(c);
});
return result;
}

Expand Down
11 changes: 9 additions & 2 deletions src/shared/Util.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "Common.h"
#include "Duration.h"

#include <cctype>
#include <string>
#include <vector>

Expand Down Expand Up @@ -335,12 +336,18 @@ inline bool isLeapYear(int year)

inline void strToUpper(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), toupper);
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c)
{
return std::toupper(c);
});
}

inline void strToLower(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), tolower);
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c)
{
return std::tolower(c);
});
}

inline wchar_t wcharToUpper(wchar_t wchar)
Expand Down

0 comments on commit 061b1ef

Please sign in to comment.