File size: 2,198 Bytes
b27bfb3 | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "cpp-ub-004", "name": "C++ UB strict aliasing and type punning"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}}
{"type": "message", "message": {"role": "user", "content": "Explain strict aliasing violations and safe type punning"}}
{"type": "message", "message": {"role": "assistant", "content": "**Strict Aliasing Violations:**\n\n**The Rule:** You cannot access an object through a pointer of a different type (with exceptions).\n\n**BAD (UB):**\n```cpp\nfloat f = 3.14f;\nint* p = reinterpret_cast<int*>(&f);\nint bits = *p; // UB! Accessing float as int\n```\n\n**BAD (UB):**\n```cpp\nunion Union {\n int i;\n float f;\n};\n\nUnion u;\nu.i = 42;\nfloat f = u.f; // UB in C++ (OK in C)\n```\n\n**SAFE Alternatives:**\n\n**1. std::bit_cast (C++20):**\n```cpp\n#include <bit>\n\nfloat f = 3.14f;\nint bits = std::bit_cast<int>(f); // Well-defined\n```\n\n**2. memcpy:**\n```cpp\n#include <cstring>\n\nfloat f = 3.14f;\nint bits;\nstd::memcpy(&bits, &f, sizeof(bits)); // Well-defined\n```\n\n**3. std::start_lifetime_as (C++23):**\n```cpp\n#include <memory>\n\nalignas(int) unsigned char storage[sizeof(int)] = {};\nint* p = std::start_lifetime_as<int>(storage);\n*p = 42; // Well-defined\n```\n\n**4. std::variant:**\n```cpp\n#include <variant>\n\nstd::variant<int, float> v = 3.14f;\nfloat f = std::get<float>(v); // Well-defined\n```\n\n**5. std::optional for nullable:**\n```cpp\n// Instead of nullptr tricks\nstd::optional<int> find_value(int key) {\n if (auto it = map.find(key); it != map.end())\n return it->second;\n return std::nullopt;\n}\n```\n\n**Compiler Flags:**\n```bash\n# Disable strict aliasing optimizations\ng++ -fno-strict-aliasing code.cpp\n\n# Or use -fwrapv for defined wrapping\ng++ -fwrapv code.cpp\n```"}}
|