Skip to content

minor bug in Utils.cpp/replaceAll(): type of index1 not 64-bit safe #1

@wenxin-wang

Description

@wenxin-wang

Hi all,
I built openbts on a 64-bit system and noticed that in the following code:

double index1 = 0;
while (index1 < output.size()) {
  try {
    index1 = output.find(search, index1);
    if (index1 == string::npos) {
        break;
    }
    output.replace(index1, search.length(), replace);
    // We want to scan past the piece we just replaced.
    index1 += replace.length();
  } catch (...) {
    LOG(ERR) << "string replaceAll error"<<LOGVAR(index1)<<LOGVAR(input)<<LOGVAR(search)<<LOGVAR(replace)<<LOGVAR(output);
    break;
  }
}

index1 of type double is compared to string::npos of type size_t and value -1, which on a amd64 machine are 32-bits and 64-bits long, respectively. So when index1 is finally set to -1, they actually have different values. This means that the if block is never triggered, and an exception is always thrown.
Since openbts has made its control file 64-bit friendly, I guess it would worth the effort to change index1 from double to size_t, and fix this issue.
Here's a little patch:

Fix type of index1 in replaceAll for 64bit safety
--- a/CommonLibs/Utils.cpp
+++ b/CommonLibs/Utils.cpp
@@ -468,7 +468,7 @@
 string replaceAll(const std::string input, const std::string search, const std::string replace)
 {
    string output = input;
-   unsigned index1 = 0;
+   size_t index1 = 0;

    while (index1 < output.size()) {
      try {

Cheers!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions