CL.SHALLOW.COPY

Freeing freed memory due to shallow copy in a copy-constructor

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 copy-constructor. Klocwork reports CL.SHALLOW.COPY 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 copy-constructor.

Vulnerability and risk

In the case of a shallow copy, a call to the copy-constructor 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

Copy
    struct D {
        /* omitted for brevity */
    };

    class C {
    public:
        C();
        ~C() {
            delete d;
       }
       C(const C& rhs) {
           d = rhs.d;    // shallow copy
       }
   private:
       C& operator=(const C&);
       D* d;
   };

In this example, a shallow copy of the member pointer d is performed within the copy-constructor. The corresponding heap memory is released in the destructor ~C(). Klocwork flags this potentially hazardous situation as CL.SHALLOW.COPY.

Fixed code example 1

Copy
    struct D {
        /* omitted for brevity */
        D(const D&);
    };

    class C {
    public:
        C();
        ~C() {
           delete d;
       }
       C(const C& rhs) {   
           d = new D(*rhs.d);
       }
   private:
       C& operator=(const C&);
       D* d;
   }; 

In the fixed example 1, a deep copy is performed in the copy-constructor; thus, no double-free can happen when destructors of the two objects are called.

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.