tinycodinglm / cpp /cpp-ub-005.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
2.7 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

Comprehensive list of undefined behavior patterns in C++

Assistant

C++ Undefined Behavior Comprehensive Patterns:

1. Signed Integer Overflow:

cpp
int x = INT_MAX;
int y = x + 1;  // UB!

2. Unsigned Integer Wraparound:

cpp
unsigned x = 0;
unsigned y = x - 1;  // OK: wraps to UINT_MAX (defined)

3. Null Pointer Dereference:

cpp
int* p = nullptr;
int val = *p;  // UB

4. Out-of-Bounds Access:

cpp
int arr[10];
int val = arr[10];  // UB (valid indices: 0-9)

5. Use After Free:

cpp
int* p = new int(42);
delete p;
int val = *p;  // UB

6. Double Free:

cpp
int* p = new int(42);
delete p;
delete p;  // UB

7. Data Races:

cpp
// Thread 1:              // Thread 2:
shared_var = 42;         int x = shared_var;  // UB!

8. Strict Aliasing Violation:

cpp
float f = 3.14f;
int* p = reinterpret_cast<int*>(&f);
int val = *p;  // UB

9. Returning Reference to Local:

cpp
int& get_value() {
    int x = 42;
    return x;  // UB!
}

10. Stack Overflow:

cpp
void infinite() {
    infinite();  // UB (eventually)
}

11. Invalid Shift:

cpp
int x = 1;
int y = x << 32;  // UB if int is 32 bits
int z = x << -1;  // UB

12. Division by Zero:

cpp
int x = 0;
int y = 10 / x;  // UB

13. Invalid Pointer Arithmetic:

cpp
int arr[10];
int* p = arr + 20;  // UB (past end)
int* p2 = arr - 1;  // UB (before begin)

14. Alignment Violation:

cpp
char buf[16];
int* p = reinterpret_cast<int*>(buf + 1);  // UB if not aligned
*p = 42;

15. Modifying String Literal:

cpp
char* s = "hello";
s[0] = 'H';  // UB

16. Accessing Volatile Incorrectly:

cpp
volatile int x = 0;
int a = x;
int b = x;  // Compiler may optimize to single read

17. Infinite Loops Without Side Effects (C++23 fix):

cpp
// C++17: UB
// C++23: OK (P2809R3)
while (true) { }