Lesson 30-C++ Advanced Debugging and Testing

Assertions

assert in the C++ Standard Library

The assert function in the C++ standard library is defined in the <cassert> header file. It takes a boolean expression as an argument. If the expression is false, it outputs an error message and terminates the program.

Basic Syntax for Using assert

#include <iostream>
#include <cassert>

int main() {
    int x = 5;
    int y = 10;

    // Check if x is less than y
    assert(x < y);  // Assertion succeeds

    x = 10;
    assert(x < y);  // Assertion fails, outputs error message and terminates the program

    return 0;
}

How assert Works

When the assert expression is false, the assert function is called, which typically prints an error message and terminates the program. For example:

assert(expression);

If expression is false, the assert function is called, which typically outputs an error message and terminates the program.

Custom Assertions

Custom assertions can provide more functionality, such as logging more context information, using different error handling mechanisms, etc.

Basic Structure of Custom Assertions

#include <iostream>
#include <cassert>

void custom_assert(bool condition, const char* message) {
    if (!condition) {
        std::cerr << "Assertion failed: " << message << std::endl;
        // Additional error handling logic can be added here
        std::abort();  // Terminate the program
    }
}

int main() {
    int x = 5;
    int y = 10;

    custom_assert(x < y, "x should be less than y");  // Assertion succeeds

    x = 10;
    custom_assert(x < y, "x should be less than y");  // Assertion fails, outputs error message and terminates the program

    return 0;
}

Extending Custom Assertions

Custom assertions can be extended to log more context information, such as file name, line number, etc.

#include <iostream>
#include <cassert>
#include <string>

void custom_assert(bool condition, const char* message, const char* file, int line) {
    if (!condition) {
        std::cerr << "Assertion failed: " << message
                  << " at " << file << ":" << line << std::endl;
        // Additional error handling logic can be added here
        std::abort();  // Terminate the program
    }
}

int main() {
    int x = 5;
    int y = 10;

    custom_assert(x < y, "x should be less than y", __FILE__, __LINE__);  // Assertion succeeds

    x = 10;
    custom_assert(x < y, "x should be less than y", __FILE__, __LINE__);  // Assertion fails, outputs error message and terminates the program

    return 0;
}

Macro Definition for Custom Assertions

To make custom assertions more convenient to use, they can be encapsulated into a macro definition.

#include <iostream>
#include <cassert>
#include <string>

#define CUSTOM_ASSERT(condition, message) \
    custom_assert((condition), (message), __FILE__, __LINE__)

void custom_assert(bool condition, const char* message, const char* file, int line) {
    if (!condition) {
        std::cerr << "Assertion failed: " << message
                  << " at " << file << ":" << line << std::endl;
        // Additional error handling logic can be added here
        std::abort();  // Terminate the program
    }
}

int main() {
    int x = 5;
    int y = 10;

    CUSTOM_ASSERT(x < y, "x should be less than y");  // Assertion succeeds

    x = 10;
    CUSTOM_ASSERT(x < y, "x should be less than y");  // Assertion fails, outputs error message and terminates the program

    return 0;
}

Example Code

Using Standard Library assert

#include <iostream>
#include <cassert>

int main() {
    int x = 5;
    int y = 10;

    assert(x < y);  // Assertion succeeds

    x = 10;
    assert(x < y);  // Assertion fails, outputs error message and terminates the program

    return 0;
}

Compilation command:

g++ -o example example.cpp

Execution command:

./example

Using Custom Assertions

#include <iostream>
#include <cassert>
#include <string>

#define CUSTOM_ASSERT(condition, message) \
    custom_assert((condition), (message), __FILE__, __LINE__)

void custom_assert(bool condition, const char* message, const char* file, int line) {
    if (!condition) {
        std::cerr << "Assertion failed: " << message
                  << " at " << file << ":" << line << std::endl;
        // Additional error handling logic can be added here
        std::abort();  // Terminate the program
    }
}

int main() {
    int x = 5;
    int y = 10;

    CUSTOM_ASSERT(x < y, "x should be less than y");  // Assertion succeeds

    x = 10;
    CUSTOM_ASSERT(x < y, "x should be less than y");  // Assertion fails, outputs error message and terminates the program

    return 0;
}

Compilation command:

g++ -o example example.cpp

Execution command:

./example

Unit Testing

Unit testing is a software development method aimed at verifying that the smallest testable units in a program (usually functions or class methods) work as expected. By writing independent test cases, it ensures that each unit functions correctly and remains correct after code modifications.

Testing Frameworks

Testing frameworks provide a set of tools for writing, organizing, and running unit tests. Common testing frameworks include Google Test, Catch2, CppUnit, etc. Among them, Google Test is one of the most widely used C++ testing frameworks.

Google Test

Google Test is a powerful and easy-to-use C++ testing framework. It provides rich assertions, test case management, and other features.

Installing Google Test Google Test can be installed through the following steps:

Download the source code:

git clone https://github.com/google/googletest.git

Compile and install:

cd googletest
mkdir build
cd build
cmake ..
make
sudo make install

Writing the First Test Case

Below is a simple example showing how to write and run test cases using Google Test.

#include <gtest/gtest.h>

// Function under test
int add(int a, int b) {
    return a + b;
}

// Test cases
TEST(AdditionTest, PositiveNumbers) {
    EXPECT_EQ(add(1, 2), 3);
    EXPECT_EQ(add(5, 7), 12);
}

TEST(AdditionTest, NegativeNumbers) {
    EXPECT_EQ(add(-1, -2), -3);
    EXPECT_EQ(add(-5, -7), -12);
}

TEST(AdditionTest, MixedNumbers) {
    EXPECT_EQ(add(-1, 2), 1);
    EXPECT_EQ(add(5, -7), -2);
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

Running Tests

Compile and run the above test cases:

g++ -o test_example test_example.cpp -lgtest -lgtest_main
./test_example

Output results:

[==========] Running 3 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 3 tests from AdditionTest
[ RUN      ] AdditionTest.PositiveNumbers
[       OK ] AdditionTest.PositiveNumbers (0 ms)
[ RUN      ] AdditionTest.NegativeNumbers
[       OK ] AdditionTest.NegativeNumbers (0 ms)
[ RUN      ] AdditionTest.MixedNumbers
[       OK ] AdditionTest.MixedNumbers (0 ms)
[----------] 3 tests from AdditionTest (0 ms total)

[----------] Global test environment tear-down
[==========] 3 tests from 1 test suite ran. (0 ms total)
[  PASSED  ] 3 tests.

Test-Driven Development (TDD)

Test-Driven Development (TDD) is a software development method whose core idea is to write test cases before writing the actual code. Through the continuous “red-green-refactor” cycle, the code is gradually improved.

Basic TDD Process

  • Write a test: First write a failing test case.
  • Make the test pass: Write enough code to make the test pass.
  • Refactor the code: Optimize the code without breaking the tests.
  • Repeat the above steps: Continue writing new test cases and make them pass.

TDD Example

Suppose we need to implement a simple stack data structure.

Write test cases

#include <gtest/gtest.h>
#include <vector>

class SimpleStack {
public:
    void push(int value) {}
    int pop() { return 0; }
    bool empty() { return true; }
};

TEST(SimpleStackTest, PushAndPop) {
    SimpleStack stack;
    stack.push(1);
    stack.push(2);
    EXPECT_EQ(stack.pop(), 2);
    EXPECT_EQ(stack.pop(), 1);
    EXPECT_TRUE(stack.empty());
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

Make the test pass

Gradually implement the SimpleStack class to make the test pass.

#include <vector>

class SimpleStack {
private:
    std::vector<int> elements;

public:
    void push(int value) {
        elements.push_back(value);
    }

    int pop() {
        if (elements.empty()) {
            throw std::runtime_error("Stack is empty");
        }
        int top = elements.back();
        elements.pop_back();
        return top;
    }

    bool empty() {
        return elements.empty();
    }
};

Refactor the code Without breaking the tests, further optimize the code, such as adding more boundary condition checks.

Static Analysis Tools

Static analysis tools analyze code before it runs to detect potential programming errors, style issues, and other code quality problems. These tools can check code during or before compilation, helping developers discover and fix issues early.

Common Static Analysis Tools

The following are several commonly used static analysis tools and their features:

  • Clang-Tidy
  • cppcheck
  • PVS-Studio

Clang-Tidy

Clang-Tidy is a static analysis tool based on LLVM and Clang. It can detect various issues in code and provide fix suggestions. Clang-Tidy can be integrated into the compilation process or used as a standalone tool.

Installing Clang-Tidy

Clang-Tidy can be installed through the following steps:

Install LLVM and Clang:

sudo apt-get update
sudo apt-get install clang-tidy

Using Clang-Tidy

Clang-Tidy can be used via the command line or integrated into build systems.

Command Line Usage

# Check a specific file
clang-tidy path/to/file.cpp -header-filter=.* -extra-arg=-std=c++11 -p=path/to/compile_commands.json

# Check the entire project
find . -name "*.cpp" | xargs clang-tidy -header-filter=.* -extra-arg=-std=c++11 -p=path/to/compile_commands.json

Integrating into CMake

Integrate Clang-Tidy in CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)
project(MyProject)

set(CMAKE_CXX_STANDARD 11)

# Generate compile commands file
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
add_executable(MyProject main.cpp)

# Add Clang-Tidy checks
enable_language(CXX)
include(CTest)
include(ClangTidy)
target_clang_tidy(MyProject "${CMAKE_CURRENT_SOURCE_DIR}/.clang-tidy" MY_PROJECT)

# Run Clang-Tidy
make clang-tidy

cppcheck

cppcheck is a lightweight static analysis tool primarily used to detect potential errors in C/C++ code. It can run before compilation and detect various types of errors.

Installing cppcheck

cppcheck can be installed with the following command:

sudo apt-get install cppcheck

Using cppcheck

cppcheck can be used via the command line:

# Check a specific file
cppcheck --enable=all --error-exitcode=1 path/to/file.cpp

# Check the entire project
find . -name "*.cpp" | xargs cppcheck --enable=all --error-exitcode=1

PVS-Studio

PVS-Studio is a commercial static analysis tool designed specifically for C/C++ code, supporting multiple platforms and IDEs. It provides detailed error reports with high accuracy and rich diagnostic capabilities.

Installing PVS-Studio

PVS-Studio can be installed through the following steps:

  • Download the installation package: Visit the PVS-Studio official website to download the installation package.
  • Install: Follow the installation wizard.

Using PVS-Studio

PVS-Studio can be integrated into Visual Studio or other IDEs.

  • Using in Visual Studio
  • Open Visual Studio.
  • Load the PVS-Studio plugin.
  • Select the project and run analysis:
  • Right-click the project -> PVS-Studio -> Analyze Project.

Command Line Usage PVS-Studio also supports command line mode:

# Check a specific file
viva64 -m32 -a path/to/file.cpp

# Check the entire project
find . -name "*.cpp" | xargs viva64 -m32 -a

Example Code

Using Clang-Tidy

Assume there is a simple C++ file example.cpp:

#include <iostream>

int main() {
    int a = 5;
    int b = 10;
    int c = a + b;
    std::cout << "Result: " << c << std::endl;
    return 0;
}

Use Clang-Tidy for checking:

# Generate compile commands file
mkdir build
cd build
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
make

# Use Clang-Tidy to check
clang-tidy ../example.cpp -header-filter=.* -extra-arg=-std=c++11 -p=.

Using cppcheck

Use cppcheck for checking:

cppcheck --enable=all --error-exitcode=1 example.cpp

Using PVS-Studio

Use PVS-Studio for checking:

viva64 -m32 -a example.cpp

Summary

Static analysis tools play an important role in the software development process. They help developers discover potential issues early, improving code quality and maintainability.

Clang-Tidy:

  • Based on LLVM and Clang, feature-rich.
  • Supports command line and CMake integration.
  • Can provide fix suggestions.

cppcheck:

  • Lightweight tool, easy to use.
  • Supports detection of multiple error types.
  • Can be used via command line.

PVS-Studio:

  • Commercial tool, powerful features.
  • Supports multiple platforms and IDEs.
  • Provides detailed error reports and high accuracy.
  • By reasonably using these static analysis tools, code quality and development efficiency can be significantly improved.

Special Tools and Techniques

Controlling Memory Allocation

Overloading new and delete

  • new expression mechanism:
string *sp = new string("a value"); // Allocate and initialize a string object
string *arr = new string[10];   // Allocate 10 default-initialized string objects
  • The above code actually performs three steps:
    • The new expression calls a standard library function named operator new (or operator new []), which allocates a sufficiently large, raw, unnamed memory space to store objects of a specific type (or an array of objects).
    • The compiler runs the corresponding constructor to construct these objects and passes initial values to them.
    • The objects are allocated space and constructed, returning a pointer to the object.
  • delete expression mechanism:
delete sp;  // Destroy *sp, then release the memory space pointed to by sp
delete [] arr;  // Destroy the elements in the array, then release the corresponding memory space
  • The above code actually performs two steps:
    • Execute the corresponding destructor for the object pointed to by sp or the elements in the array pointed to by arr.
    • The compiler calls the standard library function named operator delete (or operator delete[]) to release the memory space.
  • When custom global operator new and operator delete functions are provided, we take on the responsibility of controlling dynamic memory allocation. These two functions must be correct. Because they are a crucial part of the entire program processing.
  • The standard library defines 8 overloaded versions of the operator new and operator delete functions:
// These versions may throw exceptions
void *operator new(size_t); // Allocate an object
void *operator new[](size_t);   // Allocate an array
void *operator delete(void*) noexcept;  // Release an object
void *operator delete[](void*) noexcept;    // Release an array

// These versions promise not to throw exceptions
void *operator new(size_t, nothrow_t&) noexcept;
void *operator new[](size_t, nothrow_t&) noexcept;
void *operator delete(void*, nothrow_t&) noexcept;
void *operator delete[](void*, nothrow_t&) noexcept;
  • Applications can customize any of the above function versions, provided that the custom versions must be located in the global scope or class scope.
  • Note: The purpose of providing new operator new and operator delete functions is to change the way memory is allocated, but in any case, they cannot change the basic meaning of the new operator and delete operator.
  • Using functions inherited from C language, malloc and free, can implement allocation and release of memory in a certain way:
#include <cstdlib>

void *operator new(size_t size) {
    if(void *mem = malloc(size))
        return mme;
    else
        throw bad_alloc();
}

void operator delete(void *mem) noexcept {
    free(mem);
}

Placement new Expression

  • The placement new(placement new) form of new should be used to pass an address. The form of placement new is as follows:
new (place_address) type
new (place_address) type (initializers)
new (place_address) type [size]
new (place_address) type [size] {braced initializer list}
// place_address must be a pointer, and in initializers provide a (possibly empty) comma-separated list of initial values that will be used to construct the newly allocated object.
  • When only a pointer-type argument is passed, the placement new expression constructs the object but does not allocate memory.
  • Calling the destructor destroys the object but does not release memory.
string *sp = new string("a value"); // Allocate and initialize a string object
sp->~string();

Runtime Type Identification

  • Runtime type identification (run-time type identification, RTTI) is implemented by two operators:
    • The typeid operator, used to return the type of an expression.
    • The dynamic_cast operator, used to safely convert a base class pointer or reference to a derived class pointer or reference.
  • Using RTTI must be done with extra care. Whenever possible, it is better to define virtual functions rather than directly taking over type management responsibilities.

dynamic_cast Operator

  • The usage forms of the dynamic_cast operator are as follows:
dynamic_cast<type*>(e)  // e must be a valid pointer
dynamic_cast<type&>(e)  // e must be an lvalue
dynamic_cast<type&&>(e) // e cannot be an lvalue
// In the above, the type must be a class type, and usually the type should contain virtual functions.
// The type of e must satisfy any one of three conditions:
// 1. The type of e is a public derived class of the target type;
// 2. The type of e is a public base class of the target type;
// 3. The type of e is exactly the target type;

// Pointer type dynamic_cast
// Assume Base class has at least one virtual function, Derived is a public derived class of Base.
if (Derived *dp = dynamic_cast<Derived*>(bp)) {
    // Use the Derived object pointed to by dp
} else {    // bp points to a Base object
    // Use the Base object pointed to by dp
}

// Reference type dynamic_cast
void f(const Base &b) {
    try {
        const Derived &d = dynamic_cast<const Derived&>(b);
        // Use the Derived object referenced by b
    } catch (bad_cast) {
        // Handle type conversion failure
    }
}
  • dynamic_cast can be performed on a null pointer, resulting in a null pointer of the required type.

typeid Operator

  • The typeid operator, which allows the program to ask an expression: What type is your object?
  • The form of a typeid expression is typeid(e), where e can be any expression or type name, and the result of the operation is a reference to a constant object. It can act on expressions of any type.
  • Usually, typeid is used to compare whether two expressions have the same type, or to compare whether the type of an expression matches a specified type:
Derived *dp = new Derived;
Base *bp = dp;

if (typeid(*bp) == typeid(*dp)) {
    // bp and dp point to objects of the same type
}

if (typeid(*bp) == typeid(Derived)) {
    // bp actually points to a Derived object
}
  • When typeid acts on a pointer (rather than the object pointed to by the pointer), the result returned is the static compile-time type of the pointer.
// The following check will always fail: the type of bp is a pointer to Base
if (typeid(bp) == typeid(Derived)) {
    // Will never execute
}

Using RTTI

  • Purpose: When implementing equality operators for classes with inheritance relationships. For two objects, if their types are the same and the corresponding data members have the same values, the two objects are equal.
// Class hierarchy
class Base {
    friend bool operator==(const Base&, const Base&);
public:
    // Interface members of Base
protected:
    virtual bool equal(const Base&) const;
    // Data members and other implementation members of Base
};

class Derived: public Base {
public:
    // Other interface members of Derived
protected:
    bool equal(const Base&) const;
    // Data members and other implementation members of Derived
};

// Type-sensitive equality operator
bool operator==(const Base &lhs, const Base &rhs) {
    // If typeid is different, return false; otherwise virtually call equal
    return typeid(lhs) == typeid(rhs) && lhs.equal(rhs);
}

// Virtual equal function
bool Derived::equal(const Base &rhs) const {
    auto r = dynamic_cast<const Derived&>(rhs);
    // Perform operations to compare two Derived objects and return the result
}

// Base class equal function
bool Base::equal(const Base &rhs) const {
    // Perform operations to compare Base objects
}

type_info Class

Enumeration Types

  • Enumeration types (enumeration) allow us to organize a set of integer constants together. Enumerations are literal constant types.
  • Scoped enumeration types: First the keyword enum class (or enum struct), followed by the enumeration type name and a comma-separated list of enumerators enclosed in braces, ending with a semicolon.
enum class open_modes {input, output, append};
  • Unscoped enumeration types (unscoped enumeration): Omit the keyword class (or struct), the enumeration type name is optional.
enum color {red, yellow, green};

enum {floatPrec = 6, doublePrec = 10, double_doublePrec = 10};

Member Pointers

Member pointers: Pointers that can point to non-static members of a class.

Data Member Pointers

  • Like other pointers, when declaring a member pointer, * is used to indicate that the declared name is a pointer. The difference from ordinary pointers is that member pointers must also include the class to which the member belongs.
// pdata can point to a string member of a constant (non-constant) Screen object
const string Screen::*pdata;

// C++11
auto pdata = &Screen::contents;
  • When initializing a member pointer or assigning to a member pointer, the pointer does not point to any data. The member pointer specifies the member but not the object to which the member belongs. The object information is provided only when the member pointer is dereferenced.
Screen myScreen, *pScreen = &myScreen;

auto s = myScreen.*pdata;

s = pScreen->*pdata;

Member Function Pointers

  • Because the function call operator has higher precedence, parentheses are essential when declaring pointers to member functions and using these pointers for function calls: (C::*p)(parms) and (obj.*p)(args).

Using Member Functions as Callable Objects

Nested Classes

  • A class can be defined inside another class; the former is called a nested class or nested type. Nested classes are often used to define classes that are part of the implementation.
  • A nested class is an independent class and has basically no relationship with the outer class. In particular, objects of the outer class and objects of the nested class are independent of each other.
  • The name of a nested class is visible in the scope of the outer class but not visible outside the scope of the outer class.

union: A Space-Saving Class

  • A union is a special class. A union can have multiple data members, but at any time only one data member can have a value. It cannot contain members of reference type and virtual functions.
// Objects of type Token have only one member, which may be of any of the following types
union Token {
    // Members are public by default
    char cval;
    int ival;
    double dval;
};

  • An anonymous union is an unnamed union, with no declarations between the right brace and the semicolon.
union {
    char cval;
    int ival;
    double dval;
};

// Can directly access its members
cal = 'c';
ival = 42;
  • Note: An anonymous union cannot contain protected or private members, nor can it define member functions.

Local Classes

  • Local class: A class that can be defined inside a function. Its type is only visible in the scope where it is defined. Unlike nested classes, the members of local classes are strictly restricted.
  • All members of a local class (including functions) must be completely defined inside the class. Therefore, the role of local classes is far different from nested classes.
  • Local classes cannot use variables in the function scope.
int a, val;
void foo(int val) {
    static inti si;
    enum loc { a = 1024, b};

    // Bar is a local class of foo
    struct Bar {
        Loc locVal; // Correct: Use a local type name
        int barVal;

        void fooBar(Loc l = a) {    // Correct: Default argument is Loc::a
            barVal = val;   // Error: val is a local variable of foo
            barVal == ::val;    // Correct: Use a global object
            barVal = si;    // Correct: Use a static local object
            locVal = b; // Correct: Use an enumeration member
        }
    };
}

Inherently Non-Portable Features

The so-called non-portable features refer to machine-dependent features. When a program containing non-portable features is transferred from one machine to another, the program usually needs to be rewritten.

Bit-fields

  • A class can define its (non-static) data members as bit-fields, containing a certain number of binary bits in a bit-field. Bit-fields are usually used when a program needs to pass binary data to other programs or hardware devices.
  • The layout of bit-fields in memory is machine-related.
  • The type of a bit-field must be integer or enumeration type. Because the behavior of signed bit-fields is determined by the specific implementation, we usually use unsigned types to hold a bit-field.
typedef unsigned int Bit;
class File {
    Bit mode: 2;
    Bit modified: 1;
    Bit prot_owner: 3;
    Bit prot_group: 3;
    Bit prot_world: 3;
public:
    enum modes {READ = 01, WRITE = 02, EXECUTE = 03};
    File &open(modes);
    void close();
    void write();
    bool isRead() const;
    void setWrite();
}

// Using bit-fields
void File::write() {
    modified = 1;
    // ...
}

void File::close() {
    if( modified)
        // ... save contents
}

File &File::open(File::modes m) {
    mode |= READ;   // Set READ by default
    // Other processing
    if(m & WRITE)   // If READ and WRITE are both open
        // Open file in read/write mode
    return *this;
}

volatile Qualifier

  • When the value of an object may be changed outside the control or detection of the program, the object should be declared as volatile. The keyword volatile tells the compiler not to optimize such objects.
  • An important difference between const and volatile is that synthetic copy/move constructors and assignment operators cannot be used to initialize volatile objects or assign from volatile objects.

Linkage Directive: extern “C”

  • C++ uses linkage directive to indicate the language used by any non-C++ function.
  • To use C++ code together with code written in other languages (including C language), we must have access to the compiler of that language, and this compiler must be compatible with the current C++ compiler.
  • Standard library functions inherited by C++ from C language can be defined as C functions, but not necessarily: Whether to use C or C++ implementation of the C standard library is up to each C++ implementation.
  • Sometimes it is necessary to compile the same source file in both C and C++. To achieve this, the preprocessor defines __cplusplus when compiling the C++ version of the program.
#ifdef __cplusplus
extern "C"
#endif
int strcmp(const char*, const char*);
Share your love