简体   繁体   中英

Valgrind and ostream operator

Why is Valgrind showing error in this code?

//  const char * constructor
String::String(const char* s) {
  size = 0;
  while(s[size] != '\0')
    ++size;
  capacity = 0;
  str = new char[size];
  for (int i = 0; i < size; ++i) {
    str[i] = s[i];
    if (size > capacity && capacity == 0) {
      ++capacity;
    } else if ((size > capacity && capacity != 0)) {
      capacity *= 2;
    }
  }
}

// overloading the ostream operator
std::ostream &operator<<(std::ostream &os, const String& other) {
  return std::operator<<(os, other.str);
}

// testing
TEST(Iostream, Out) {
  std::stringstream os;
  String s = "lol";
  os << s;
  ASSERT_EQ(os.str(), "lol");
}

// main function for testing
int main() {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

//////////////////////////////////////////////////////////////// Why is strlen showing here if I haven't used it anywhere?

==11274== Invalid read of size 1
==11274==    at 0x48425F4: strlen (vg_replace_strmem.c:469)
==11274==    by 0x49BCBCD: std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28)

Why is strlen showing here if I haven't used it anywhere?

return std::operator<<(os, other.str);

This is the same function that is called when you do:

void foo(std::ostream& stream, const char * ptr) {
  stream << ptr;
}

How else is the stream supposed to know the length of the passed null-terminated string if not via a strlen() or something equivalent?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM