CL.SELF-ASSIGNFreeing freed memory due to missing self-assignment checkThis 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 riskSelf-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 11 class Pencil { 2 }; 3 class Box { 4 public: 5 Box& operator=(const Box& rhs) { 6 count = rhs.count; 7 delete x; 8 x = new Pencil(*rhs.x); 9 } 10 private: 11 int count; 12 Pencil *x; 13 }; 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 11 class Pencil { 2 }; 3 class Box { 4 public: 5 Box& operator=(const Box& rhs) { 6 if (this==&rhs) return *this; 7 count = rhs.count; 8 delete x; 9 x = new Pencil(*rhs.x); 10 } 11 private: 12 int count; 12 Pencil *x; 14 }; In the fixed example, line 6 has the check for assignment to self. Related checkersExternal guidanceExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |