CodeQL documentation

Unsafe use of this in constructor

ID: cpp/unsafe-use-of-this
Kind: path-problem
Severity: error
Precision: very-high
Tags:
   - correctness
   - language-features
   - security
   - external/cwe/cwe-670
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

This rule finds calls to pure virtual member functions in constructors and destructors. When executing the body of a constructor of class T, the virtual table of T refers to the virtual table of one of T’s base classes. This can produce unexpected behavior, including program abort that can lead to denial of service attacks. The same problem exists during destruction of an object.

Recommendation

Do not rely on virtual dispatch in constructors and destructors. Instead, each class should be responsible for acquiring and releasing its resources. If a base class needs to refer to a derived class during initialization, use the Dynamic Binding During Initialization idiom.

Example

class Base {
private:
    // pure virtual member function used for initialization of derived classes.
    virtual void construct() = 0;
public:
    Base() {
        // wrong: the virtual table of `Derived` has not been initialized yet. So this
        // call will resolve to `Base::construct`, which cannot be called as it is a pure
        // virtual function.
        construct();
    }
};

class Derived : public Base {
    int field;

    void construct() override {
        field = 1;
    }
};