From 3e0c04a83e99847e5e846ce8c198bb8a5d26343f Mon Sep 17 00:00:00 2001 From: lioncash Date: Fri, 5 Sep 2014 14:34:46 -0400 Subject: [PATCH] Common: Fix a potential infinite loop in ReplaceAll Prior to this change, it was possible to cause an infinite loop by making the string to be replaced and the replacing string the same thing. e.g. std::string some_str = "test"; ReplaceAll(some_str, "test", "test"); This also changes the replacing in a way that doesn't require starting from the beginning of the string on each replacement iteration. --- Source/Core/Common/StringUtil.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Source/Core/Common/StringUtil.cpp b/Source/Core/Common/StringUtil.cpp index 3239628b62..91d451a03f 100644 --- a/Source/Core/Common/StringUtil.cpp +++ b/Source/Core/Common/StringUtil.cpp @@ -281,12 +281,17 @@ std::string TabsToSpaces(int tab_size, const std::string &in) std::string ReplaceAll(std::string result, const std::string& src, const std::string& dest) { - while (1) + size_t pos = 0; + + if (src == dest) + return result; + + while ((pos = result.find(src, pos)) != std::string::npos) { - size_t pos = result.find(src); - if (pos == std::string::npos) break; result.replace(pos, src.size(), dest); + pos += dest.length(); } + return result; }