I’m coding my version of the String class, but Valgrind whines about my implementation of the << operator for my string. The error is at the wrong line, if I print char by char it works great.
Where am I wrong?
Valgrind error:
==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)
My << operator for string:
ostream & operator << (ostream & o, String & inS) {
o << inS._pData << " "; // the wrong line
return o;
}
My String class:
class String {
public:
unsigned _size;
char * _pData;
String();
String(const char* inCString);
};
Constructor (for 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;
}
I don’t recommend using raw strings like this.
However, the culprit is here:
Or, alternatively, store the NUL-termination character manually:
By missing the NUL-termination character, the output operation will just keep on running past the end of the string. (The behaviour may happen to look okay, since the character may be nul by chance, depending on compiler, options etc.)
Hint:
char*, at least usestdrupandfreeif you insist on doing NUL-terminated strings, consider writing that the C++ way too: