tinycodinglm / cpp /cpp-ub-003.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
1.77 kB
opencode trace
System 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 c...

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.

User

Deep dive into signed integer overflow UB and compiler optimizations

Assistant

Signed Integer Overflow UB:

The Problem:

cpp
// This code has UB
int x = INT_MAX;
int y = x + 1;  // Overflow = UB

// Compiler may optimize:
// if (x + 1 > x) return 1;
// to:
// return 1;  // always true

Real-World Exploits:

cpp
// Linux kernel CVE-2016-9793
// Signed overflow allowed privilege escalation

// GCC bug 68125
// Signed overflow UB enabled dead code elimination

Detection:

bash
# UBSan catches this
g++ -fsanitize=undefined code.cpp
./a.out
# code.cpp:3:5: runtime error: signed integer overflow

Safe Alternatives:

cpp
// 1. Use unsigned
unsigned int x = UINT_MAX;
unsigned int y = x + 1;  // wraps to 0 (defined)

// 2. Check before overflow
if (x > INT_MAX - 1) { /* handle */ }
int y = x + 1;

// 3. Use checked arithmetic (C++26)
#include <stdckdint>
int result;
bool overflow = ckd_mul(&result, a, b);

// 4. Use safe numerics library
#include <safe_numerics.hpp>
auto result = safe_cast<int>(big_number);