SdtElectronics
SdtElectronics

Reputation: 586

Is writing to uninitialized memory allocated by allocator UB? And what about reading it afterwards?

struct Foo{ 
    int i;
    int j;
};

int main(){ 
    std::allocator<Foo> bar;
    Foo* foo = bar.allocate(1);
    foo->i = 0;
    return foo->i; // ignore the memory leak, it's irrelevant to the question
}

I'm curious about whether there are undefined behaviors in the snippet above? Will the conclusion vary according to the type of Foo (e.g. not all members are POD type, or Foo has virtual functions)?

Upvotes: 1

Views: 199

Answers (1)

user12002570
user12002570

Reputation: 1

It is an error to use raw memory in which an object has not been constructed. We must construct objects in order to use memory returned by allocate. Using unconstructed memory in other ways is undefined. Source: C++ Primer, Fifth Edition

Since you have not used construct the behavior of your program is undefined prior to C++20.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

Upvotes: 1

Related Questions