[英]Valgrind and ostream operator
為什么 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();
}
///////////////////////////////////////////////// ///////////// 如果我沒有在任何地方使用過 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)
如果我沒有在任何地方使用過 strlen,為什么會在此處顯示?
return std::operator<<(os, other.str);
這與您執行以下操作時調用的函數相同:
void foo(std::ostream& stream, const char * ptr) {
stream << ptr;
}
如果不是通過strlen()
或等效的東西,流應該如何知道傳遞的以空字符結尾的字符串的長度?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.