Frage

recently I implemented a custom function for trimming std::strings that removes whitespace character prefixes and suffixes.

I tested the functionality and it works according to my unit tests, but when run the tests using valgrind, I get the following output:

==4486== Conditional jump or move depends on uninitialised value(s)
==4486==    at 0x415DDA: is_ws_char(char) (parse.cpp:22)
==4486==    by 0x415BC6: parse::trim(std::string&) (parse.cpp:34)

My input test string was

string s("  a");

I do not see what is the problem here. The code looks like this:

inline bool is_ws_char(const char c) {    // this is line 22 in my code
  return (c == ' ' || c == '\n' || c == '\t' || c == '\r');
}


void parse::trim(std::string& str) {
  size_t len = str.size();
  size_t i = 0;
  for (; i < len; ++i)
    if (!is_ws_char(str[i]))
      break;
  const size_t start = i;
  for (i = len - 1; i >= 0; --i)
    if (!is_ws_char(str[i]))              // this is line 34 in my code
      break;
  const size_t end = i;
  str = str.substr(start, end - start + 1);
}

Does anybody has an idea what is the problem here? I briefly thought that is's just a valgrind oddity, but that seems to be rather unlikely.

Thanks in advance!

War es hilfreich?

Lösung

This loop is invalid

for (i = len - 1; i >= 0; --i)

The condition will be always equal to true because expression --i will be always >= 0 due to the fact that i is unsigned integer.

Also when str.size() is equal to zero then len - 1 will be equal to std::string::npos.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top