简体   繁体   中英

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 (eg not all members are POD type, or Foo has virtual functions)?

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 anything 1 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.


1 For 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM