cppadvanced15 minutes

Fix the Memory Leak and Logical Errors in a Custom Smart Pointer Implementation

Identify and fix memory management bugs and logical errors in a custom C++ shared pointer implementation to ensure proper resource deallocation and reference counting.

Challenge prompt

The provided code is a basic implementation of a shared_ptr-like class in C++. However, it contains critical bugs that cause memory leaks, double-deletions, and incorrect reference counting. Your task is to identify and fix these bugs to make the smart pointer behave correctly and manage the resource safely with proper reference counting.

Guidance

  • Examine the destructor and copy assignment operator for proper handling of reference counts.
  • Ensure that the resource is deleted only when the last shared_ptr pointing to it is destroyed or reset.
  • Check for unsafe usage of raw pointers and dangling pointer risks.

Hints

  • Consider the rule of three: destructor, copy constructor, and copy assignment operator need to be consistent.
  • Reference count deletion and pointer nullification should happen atomically when count reaches zero.
  • Avoid deleting pointers multiple times; track ownership carefully.

Starter code

template <typename T>
class SharedPtr {
private:
    T* ptr;
    int* count;
public:
    SharedPtr(T* p = nullptr) : ptr(p), count(new int(1)) {}

    ~SharedPtr() {
        (*count)--;
        if (*count == 0) {
            delete ptr;
            delete count;
        }
    }

    SharedPtr(const SharedPtr& sp) {
        ptr = sp.ptr;
        count = sp.count;
        (*count)++;
    }

    SharedPtr& operator=(const SharedPtr& sp) {
        if (this != &sp) {
            if (--(*count) == 0) {
                delete ptr;
                delete count;
            }
            ptr = sp.ptr;
            count = sp.count;
            (*count)++;
        }
        return *this;
    }
    T& operator*() { return *ptr; }
    T* operator->() { return ptr; }
};

Expected output

Correct behavior is no memory leaks or double deletions during usage. The pointer resource should be deleted exactly once when no SharedPtr objects reference it anymore.

Core concepts

C++ pointersmemory managementreference countingcopy constructor and assignmentdestructor

Challenge a Friend

Send this duel to someone else and see if they can solve it.