Search code examples
c++pointersc++11vectorraii

Why Pointer contains some trash?


I have the 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 my pointer contains not only d. How to create pointer with 5 symbols of d with RAII?


Solution

  • Because container.data() is not null-terminated, so that pointer doesn't point to a C-style string. You've put 5 ds there, but after those bytes is just unallocated memory. When you try to stream it, it'll just keep going until one of those unallocated bytes happens to be a \0.

    In order to print a const char* validly, it has to end with a \0. You can verify that with:

    size_t size = 5;
    std::vector<char> container(size, 'd');
    
    container.push_back('\0');
    std::cout << container.data();
    

    Same thing for str_. You allocated enough memory for the null-terminator, you just had to add it:

    char* str_ = new char[size + 1];
    memcpy(str_, container.data, size * sizeof(char));
    str_[size] = '\0'; // need this