我正在編寫我的版本的字符串類,但Valgrind抱怨我的我的字符串執行<<
運算符。錯誤是在錯誤的行,如果我打印字符char它工程很好。條件跳轉valgrind與char *和<<運算符
我在哪裏錯了?
Valgrind的錯誤:
==2769== Conditional jump or move depends on uninitialised value(s)
==2769== at 0x4C2AC28: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2769== by 0x4ECAD60: std::basic_ostream >& std::operator<< >(std::basic_ostream >&, char const*) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.17)
==2769== by 0x400BD5: operator<<(std::ostream&, String&) (string.cpp:22)
==2769== by 0x400AAC: main (main.cpp:12)
我<<
操作字符串:
ostream & operator << (ostream & o, String & inS) {
o << inS._pData << " "; // the wrong line
return o;
}
我String
類:
class String {
public:
unsigned _size;
char * _pData;
String();
String(const char* inCString);
};
構造函數(用於char*
):
String::String(const char* inCString) {
_size = strlen(inCString);
_pData = new char[_size + 1];
strncpy(_pData, inCString, _size);
}
Main.cpp的:
int main(int, char**) {
String s1("hello");
cout << s1;
return 0;
}
請問爲什麼你要重新實現字符串的麻煩? – Benj
你是否遵守[Rule of Three](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming))? –
@MooingDuck:是的,但不是整個代碼在這裏;只有相關的。 – bagage