From 4d0a2a2aeffaf7bef08c8535568c1f4d3ae03217 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=ADn=20Knoblauch=20Revuelta?= Date: Thu, 7 Mar 2019 20:41:53 +0100 Subject: [PATCH] Fix union example taken from TC++PL4 (#1357) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- CppCoreGuidelines.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index dadf5de..02293bb 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -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; }