c++ - Why Pointer contains some trash? -
i have following code snippet:
size_t size = 5; std::vector<char> container(size, 'd'); std::copy(container.begin(), container.begin() + size, std::ostream_iterator<char>(std::cout, " ")); // d d d d d auto ptr = containter.data(); //ptr == dddddtrashtrash why?? char* str_ = new char[size + 1]; memcpy(str_, container.data, size * sizeof(char)); std::cout << str_ << std::endl; // dddddtrashtrashtrash!!!!
i don't understand, why pointer contains not d
. how create pointer 5
symbols of d
raii
?
because container.data()
not null-terminated, pointer doesn't point c-style string. you've put 5 d
s there, after bytes unallocated memory. when try stream it, it'll keep going until 1 of unallocated bytes happens \0
.
in order print const char*
validly, has end \0
. can verify with:
size_t size = 5; std::vector<char> container(size, 'd'); container.push_back('\0'); std::cout << container.data();
same thing str_
. allocated enough memory null-terminator, had add it:
char* str_ = new char[size + 1]; memcpy(str_, container.data, size * sizeof(char)); str_[size] = '\0'; // need
Comments
Post a Comment