Fix union example taken from TC++PL4 (#1357)

The code fails to set the type when a number value is assigned to a (formerly) string value. As a result, later access to the value or destruction of the object cause undefined behaviour (access to arbitrary memory address and/or heap corruption). The string field of the union is accessed, but its the number what is there…

It's also wrong in the book!

The fact that this bug has survived so long pretty much proves the point that code with unions is hard to get right ;-)

Oh, by the way, in order to test this, I had to add a constructor. Though, I'm not including it in the change. I suppose this just stuff we take for granted in the "// …" comment.
This commit is contained in:
Martín Knoblauch Revuelta 2019-03-07 20:41:53 +01:00 committed by Herb Sutter
parent f5689ada23
commit 4d0a2a2aef

View File

@ -8584,9 +8584,9 @@ Saving programmers from having to write such code is one reason for including `v
break;
case Tag::text:
new(&s) string(e.s); // placement new: explicit construct
type = e.type;
}
type = e.type;
return *this;
}