Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relying on a zero'ing heap for initialising members

Is it well defined behavoir to rely on a heap which zero initialises memory to initialise members to zero.

Looking at a basic POD struct:

struct S {int i;};

If I have (through whatever mechanism) a heap implementation which guarantees to zero out the backing memory, can I avoid zeroing out the members of my POD?

Another way to put this - is the following well defined behaviour:

#include <cstdlib>
#include <cstring>
#include <memory>
#include <assert.h>
struct S {int i;};
int main()
{
    void* backing_mem = std::aligned_alloc(alignof(S), sizeof(S));
    std::memset(backing_mem, 0, sizeof(S));
    S* s = new (backing_mem)S;
    assert(s->i == 0);

    // or assuming we've overridden the global allocator to one which zeros memory:
    S* s2 = new S;
    assert(s2->i == 0);
}

Link: https://godbolt.org/z/M6oY9q5xW

I understand the language has exceptions for global/statically allocated objects to be implicitly zero, and was wondering if the same happens here. Obviously this wont work for non-PODs. Please quote the standard if possible.

(Please ignore talk about optimisation here, this is a language/correctness question)

like image 999
Mike Vine Avatar asked Oct 25 '25 08:10

Mike Vine


1 Answers

Is it well defined behavoir to rely on a heap which zero initialises memory to initialise members to zero.

From a standard perspective: no.

Whilst you're fine from a lifetime perspective ([basic.life]/6) the s->i is an uninitialized read which is, as per [basic.indet]/2, undefined behaviour.

[basic.indet]/1 When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced ([expr.ass]).

[basic.indet]/2 If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:

  • [... none applies here]
like image 97
dfrib Avatar answered Oct 27 '25 00:10

dfrib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!