0

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?

Museful
  • 6,711
  • 5
  • 42
  • 68
  • @Slava `std::array` is on stack and wouldn't `new char[]` initialize the memory? – Museful Jun 26 '18 at 22:16
  • `new` is not required to initialize embeded types, but in dev environment `malloc` may do it, so you would not win anything by using it vs `new` – Slava Jun 26 '18 at 22:27

2 Answers2

4

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 );
Slava
  • 43,454
  • 1
  • 47
  • 90
3

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

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • Wouldn't `new char[]` initialize the memory? – Museful Jun 26 '18 at 22:17
  • @Museful Not as far as I know. Primitive types and POD types don't automatically initialize. – Zan Lynx Jun 26 '18 at 22:18
  • 1
    @Museful No, it does not initialize the memory (or at least, there's no guarantee) https://stackoverflow.com/a/7546745/1896169 – Justin Jun 26 '18 at 22:28
  • 2
    Just a note: allocating a lot of memory often confuses newbies because it *does* look like it got set to zero. But this is not a C or C++ guarantee; it happens because the C support library (msvcrt or glibc) requests a new block of memory from the operating system. Which is set to all zeroes for security reasons. – Zan Lynx Jun 26 '18 at 22:31