Is it safe to access a `std::vector`'s reserved but not sized-in memory, as raw memory?

144 views Asked by At

If one wants to allocate a block of memory without initializing it to zeros, is it safe to do the following?

std::vector<uint8_t> block(0);
block.reserve(10000000);
// now access block.data()[0] through block.data()[9999999] as raw uninitialized memory

If not, is there a more recent tool for this job, than malloc and free?

2

There are 2 answers

4
Slava On BEST ANSWER

If you have compile time constant and relatively small size you can use std::array:

std::array<uint8_t,10000> block;

if not use raw memory:

std::unique_ptr<uint8_t[]> block( new uint8_t[size] );

or after c++14

auto block = std::make_unique<uint8_t[]>( size );
4
Zan Lynx On

It might be "safe" but you are breaking the class design. And in some standard C++ support libraries, the vector and its iterators will call abort() in debug mode because you violated invariant asserts.

So don't do it.

If you just want big uninitialized blocks you can still use new char[size] and unique_ptr