Since the question is tagged C++, here's an important note on filling uninitialized memory. When in need to create objects in a range that was created without calling constructors, you need to use std::uninitialized_fill
. This algorithm essentially calls placement new on the "buffer slots" to first enforce a constructor call on the buffer elements. This process is very important in cases where the buffer was created by calling e.g. malloc
that is unaware of constructors and performs both steps of constructing and initializing. You can ignore this when initializing trivial types.
When there's a specific value you want to populate with, use std::fill
.
std::fill(buffer, buffer + buffer_sz, value);
When in need to create elements according to some policy use std::generate
:
std::generate(buffer, buffer + buffer_sz, [] {
/* generate some value */
} );
Both solutions assume your buffer is strongly typed, i.e. ++buffer
will point to the next element in the range. For void*
buffers this means you have to cast the iterator to the appropriate type, e.g. :
std::fill(
static_cast<int*>(buffer), // Creates a strongly typed iterator
static_cast<int*>(buffer + buffer_size),
value);
That been said, note that for specific uses the standard library offers specialized algorithms, e.g. theres std::iota
if you want to fill a range with sequence.