1
struct A { //POD class
    char data[10];
    void print() {std::cout << data;}
};
int main() {
    char buffer[11] = "HELLO"; //sets values in buffer
    A* a = new(buffer)A;
    a->print(); // read from memory buffer
    a->~A();
}

From the class' perspective, this is a read from uninitialized memory, but from the memory perspective, the memory was actually initialized. Is this undefined behavior, or merely dangerous?

[Note: For those curious about new(buffer)A and a->~A(), This is called "placement new" and is used to construct objects in a specific buffer in memory. This is was vector does under the covers to construct classes in its internal buffer]

12

3 Answers 3

8

Even though the class member and the array are guaranteed to have the same address in this particular case (based on [basic.compound]/4.3 plus the fact that the requirements on new-expressions don't really allow the compiler to do anything else than put that object right at the beginning of your buffer), I'm pretty sure this is undefined behavior.

I believe the relevant bit of the standard would be basic.memobj §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]).

I'm not aware of any additional wording anywhere in the standard that would in any case give guarantees concerning the initial value of an object based on what was inside the storage it was created in before its lifetime began. Your object is default-initialized and of class type, therefore, the default constructor will be called. There is no mem-initializer for the member in your constructor nor is there a default initializer in the class, therefore, the member will be default-initialized [class.base.init/9.3]. Since the elements of the array are of fundamental type, no initialization will be performed for them. That means that basic.indet §2 applies to any use of the contents of the array (which would happen inside the operator <<)

If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases […]

Since your case does not match any of the cases listed as exceptions, your program should have undefined behavior…

4
  • This is my reasoning too. Although I'm annoyed that I can't get any of the sanitizers to complain about this code (then again I also can't get any of the sanitizers to complain about int i; cout << i; so ... shrug)
    – Barry
    Dec 12, 2018 at 18:15
  • 1
    Unfortunately, this case is a bit hard for a sanitizer to detect. I guess the only way to do it in general would be to create some internal data structure that keeps track of every uninitialized object and generate code that queries that data structure upon every access to an lvalue anywhere in the program. Even for a sanitizer, that overhead might be a bit too massive… Dec 12, 2018 at 18:34
  • Now I'm idly wondering about assigning the buffer from the already initialized buffer it's built into: coliru.stacked-crooked.com/a/4c926413da81a529 Curiously, G++ is not producing output for this variation. Dec 12, 2018 at 18:34
  • 3
    I think this also constitutes UB because (as also noted by n.m. in his comment to your original question), the lifetime of the elements of your buffer has ended and their storage is being reused at the point your constructor is called… Dec 12, 2018 at 18:41
2

The state of the buffer after the object is constructed is undefined. Compilers are free to write "format c;:" into it during construction of A. They are also free to optimize your preloading of the buffer out, simply discarding what you did on that line.

Your print code is then UB as << expects a nul-terminated buffer.

1

Although it would generally cost nothing for a compiler to interpret a placement new as "importing" whatever bit patterns happen to be in the storage before an object is constructed, there are some difficult-to-characterize corner cases where doing so may significantly complicate or impede optimization without offering any real benefit. Thus, the Standard allows compilers to import the bit patterns in cases where it would cost nothing or would benefit their customers, without requiring them to do so in cases that would be expensive without benefiting their customers.

While it would be helpful if there were a form of placement new syntax that would explicitly specify that bit patterns should be imported, such a thing wasn't seen as necessary when the Standard was written. In most cases where importing bit patterns would be useful, it would cost nothing and compilers would do it whether mandated or not. In cases where it would be useless, it wouldn't matter whether compilers supported the behavior. Situations where such a syntax would result in compilers doing something useful that they wouldn't otherwise do were sufficiently rare that there was no need to accommodate them.

Obviously, compiler philosophy has changed in the decades since placement new was first standardized, and situations where bitwise import would be useful but compilers wouldn't reliably support it are far more commonplace. A sensible resolution would be to add two new syntactic forms--one which would require that a compiler import the bit pattern and another which would explicitly state that the bit pattern didn't matter--on the basis that the programmer will likely know more about whether the bit patterns matter than a compiler writer possibly could. So far, however, that hasn't happened yet, leaving constructs like yours in the awkward state of being usefully supported by some implementations but not others, without any nice way of identifying implementations that support them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.