Code Checking Tools

Code Checking Tools

Today we will talk about tools that will help you find bugs in your code.

  • Valgrind’s Memcheck Tool
  • Clang: Not just a compiler

Valgrind is all-in-one, but Clang is (much) faster.

The lab installs of Clang are broken... so we won't be using them today.

Stack and Heap

  • The stack (on x86) starts at a high address and grows down
  • The heap (on x86) starts at the bottom and grows up
  • Destructors on stack-allocated class instances are called when the function returns
  • Destructors on heap-allocated class instances are called when delete is called on the pointer

Uninitialized Values

Uninitialized Values

  • Reading a value that hasn’t been initialized from the stack or the heap.
  • Especially dangerous when program flow depends on that value.

Valgrind

  • valgrind --track-origins=yes
  • Slower, but keeps track of where uninitialized values were allocated.

Clang Memory Sanitizer

  • Compile your program with the right features turned on
    • clang++ --fsanitize=memory
    • --fsanitize-memory-track-origins
    • It's one command... but this slide is too narrow to hold it.
  • Set the right shell variables
    • source symbolizer.sh
  • Run the program

Invalid Reads and Writes

Invalid Reads and Writes (valgrind and address-sanitizer)

  • Reading or writing values from unallocated memory.
  • Sometimes may result in a segfault, but not always.

Valgrind

  • Valgrind isn’t perfect: you can read and write to things on the stack without complaint.

Clang Address Sanitizer

  • Compile your program with the right features turned on
    • clang++ --fsanitize=address
  • Set the right shell variables
    • source symbolizer.sh
  • Run the program

Invalid and Mismatched deletes

Invalid and Mismatched deletes

  • Mismatched delete: using delete with new[] or vice versa.
  • Double delete: deleting the same memory twice

Memory Leaks

Valgrind

  • Valgrind runs leak checks after the program terminates.
  • Directly lost: No pointer to that block anymore.
  • Indirectly lost: A pointer to that block exists, but it’s in a directly lost block.
  • Still reachable: Still have a pointer to that block.
  • Possibly lost: No pointer to the beginning of the block, but a pointer to somewhere inside the block.
  • valgrind --leak-check=full
  • Valgrind Memcheck Manual