Why does the pointer contain garbage?
I have the following piece of code:
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 more than just d
. How to create an index with 5
symbols d
using RAII
?
source to share
Because it container.data()
doesn't end in zero, so the pointer doesn't point to a C style string. You put 5 there d
, but after those bytes are just unallocated memory. When you try to transfer it, it will keep running until one of those unallocated bytes is gone \0
.
To print a const char*
valid, it must end in \0
. You can check that with:
size_t size = 5;
std::vector<char> container(size, 'd');
container.push_back('\0');
std::cout << container.data();
The same goes for str_
. You allocated enough memory for the null terminator, you just needed to add it:
char* str_ = new char[size + 1];
memcpy(str_, container.data, size * sizeof(char));
str_[size] = '\0'; // need this
source to share
... why does my pointer contain not only
d
Ok, as Barry showed, your pointer actually only contains d
s
And about your second question,
How do I create a 5 character d pointer with RAII?
You can use unique_ptr:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <memory>
int main()
{
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
std::cout << '\n';
std::unique_ptr<char[]> p(new char[size]);
for(size_t i=0; i<size; ++i)
p[i] = 'd';
for(size_t i=0; i<size; ++i)
std::cout << p[i] << ' ';
std::cout << '\n';
}
(By the way, the code snippet doesn't compile)
source to share