简体   繁体   English

Valgrind 和 ostream 运算符

[英]Valgrind and ostream operator

Why is Valgrind showing error in this code?为什么 Valgrind 在这段代码中显示错误?

//  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? ///////////////////////////////////////////////// ///////////// 如果我没有在任何地方使用过 strlen 为什么会在这里显示?

==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?如果我没有在任何地方使用过 strlen,为什么会在此处显示?

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?如果不是通过strlen()或等效的东西,流应该如何知道传递的以空字符结尾的字符串的长度?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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