tinycodinglm / cpp /cpp-sanitizers-001.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame Contribute Delete
2.78 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 guide to C++ sanitizers (ASan, UBSan, TSan, MSan)

Assistant

C++ Sanitizers Comprehensive Guide:

1. AddressSanitizer (ASan):

bash
# Compile
g++ -fsanitize=address -fno-omit-frame-pointer -g code.cpp

# Run
./a.out

# Environment variables
ASAN_OPTIONS=detect_leaks=1 ./a.out

Detects:

  • Buffer overflow (stack, heap)
  • Use-after-free
  • Use-after-return
  • Double-free
  • Memory leaks

2. UndefinedBehaviorSanitizer (UBSan):

bash
# Compile
g++ -fsanitize=undefined -g code.cpp

# With specific checks
g++ -fsanitize=signed-integer-overflow,null,alignment,bool,array-bounds,enum,float-cast-overflow,float-divide-by-zero,function,implicit-integer-sign-change,implicit-signed-integer-truncation,implicit-unsigned-integer-truncation,integer-divide-by-zero,nonnull-attribute,null,pointer-overflow,return,shift,assign,bool,enum,float-divide-by-zero,function,integer-divide-by-zero,nonnull-attribute,null,pointer-overflow,return,shift,bool,enum -g code.cpp

Detects:

  • Signed integer overflow
  • Null pointer dereference
  • Alignment violations
  • Out-of-bounds array access
  • Invalid shift operations

3. ThreadSanitizer (TSan):

bash
# Compile
g++ -fsanitize=thread -g code.cpp

# Run
./a.out

Detects:

  • Data races
  • Deadlocks
  • Order violations

4. MemorySanitizer (MSan):

bash
# Compile
g++ -fsanitize=memory -fPIE -pie -g code.cpp

# Run
./a.out

Detects:

  • Use of uninitialized memory

5. LeakSanitizer (LSan):

bash
# Compile with ASan (included)
g++ -fsanitize=address -g code.cpp

# Or standalone
ASAN_OPTIONS=detect_leaks=1 ./a.out

Combining Sanitizers:

bash
# ASan + UBSan
g++ -fsanitize=address,undefined -g code.cpp

# TSan (cannot combine with ASan/MSan)
g++ -fsanitize=thread -g code.cpp

CI Integration:

yaml
# GitHub Actions
- name: Build with sanitizers
  run: |
    g++ -fsanitize=address,undefined -fno-omit-frame-pointer -g code.cpp
    ./a.out
  env:
    ASAN_OPTIONS: detect_leaks=1
    UBSAN_OPTIONS: print_stacktrace=1