i'm trying implement c_str() function of custom string class. seems work, reason prints "=" in end of every string:
const char* c_str() { char* temp = alloc.allocate(data.size() + 1); uninitialized_copy(data.begin(), data.end(), temp); temp[data.size()+1] = '\0'; return temp; } private part of str class:
private: vec<char> data; allocator<char> alloc; *vec vector.
int main() { str s1 = "hello, beee"; cout << s1.c_str(); return 0; } where wrong?
the problem here:
temp[data.size() + 1] = '\0'; the char array allocated data.size() + 1 bytes, indices should 0 data.size(). temp[data.size() + 1] out of array boundary. code may lead undefined behaviors.
it should be
temp[data.size()] = '\0';
Comments
Post a Comment