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

1    struct D {
2        /* omitted for brevity */
3    };
5    class C {
6    public:
7        C();
8        ~C() {
9            delete d;
10       }
11       C& operator=(const C& rhs) {
12           d = rhs.d;    // shallow copy
13           return *this;
14       }
15   private:
16       C(const C&);
17       D* d;
18   };                 

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

1    struct D {
2       /* omitted for brevity */
3       D(const D&);
4    };
6    class C {
7    public:
8        C();
9        ~C() {
10           delete d;
11       }
12       C& operator=(const C& rhs) {
13           d = new D(*rsh.d);
14           return *this;
15       }
16   private:
17       C(const C&);
18       D* d;
19   };         

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.

Security training

Application security training materials provided by Secure Code Warrior.


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