CL.SHALLOW.ASSIGN
Freeing freed memory due to shallow copy in an assignment operator
This is a class-level (CL) checker that notifies of potential for a double-freeing of heap memory by the class destructor due to the shallow copy in operator=. Klocwork reports CL.SHALLOW.ASSIGN when a class destructor performs release of a dynamic memory pointed by one or more of its data members when only a shallow copy of these pointers is performed in the assignment operator.
Vulnerability and risk
In the case of a shallow copy, a call to the assignment operator will result in two objects having data members pointing to the same dynamic memory. Without a proper reference counting device, when the first object goes out of scope, the class destructor will release the memory shared between the two objects. The appropriate data members of the second object will point to the now deleted memory locations. Upon the second object going out of scope, its destructor will attempt to release this memory again. This can lead to application crashes and/or heap memory corruption.
Vulnerable code example 1
struct D {
/* omitted for brevity */
};
class C {
public:
C();
~C() {
delete d;
}
C& operator=(const C& rhs) {
d = rhs.d; // shallow copy
return *this;
}
private:
C(const C&);
D* d;
};
In this example, a shallow copy of the member pointer d is performed within the operator=. The corresponding heap memory is released in the destructor ~C(). Klocwork flags this potentially hazardous situation as CL.SHALLOW.ASSIGN.
Fixed code example 1
struct D {
/* omitted for brevity */
D(const D&);
};
class C {
public:
C();
~C() {
delete d;
}
C& operator=(const C& rhs) {
d = new D(*rsh.d);
return *this;
}
private:
C(const C&);
D* d;
};
In the fixed example 1, a deep copy is performed in the operator=; therefore, no double-free can happen when destructors of the two objects are called.
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.