CL.SELF-ASSIGN
Freeing freed memory due to missing self-assignment check
This is a class-level (CL) checker that notifies you of potential assignment to self in operator=. Class-level checkers produce recommendations based on Scott Meyer's rules for effective C++ class construction.
Vulnerability and risk
Self-assignment within an assignment operator can lead to member data corruption. Dynamically allocated member data, specifically, can be inadvertently deleted or lost when such an assignment takes place.
Vulnerable code example 1
class Pencil {
};
class Box {
public:
Box& operator=(const Box& rhs) {
count = rhs.count;
delete x;
x = new Pencil(*rhs.x);
}
private:
int count;
Pencil *x;
};
In this example, there is no check within the operator= for assignment to self. Should self-assignment take place, the delete operator at line 7 deletes member 'x' from parameter 'rhs' (which is operating as an alias to 'this'), resulting in corrupted memory being used in the copy constructor at line 8.
Fixed code example 1
class Pencil {
};
class Box {
public:
Box& operator=(const Box& rhs) {
if (this==&rhs) return *this;
count = rhs.count;
delete x;
x = new Pencil(*rhs.x);
}
private:
int count;
Pencil *x;
};
In the fixed example, line 6 has the check for assignment to self.
Related checkers
External guidance
Security training
Application security training materials provided by Secure Code Warrior.
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.