Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

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

1  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 1

1  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.

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.