Restrict dynamic deletion of objects created on stack

Restricting dynamic deletion of objects created on stack

In this article we will discuss about restricting dynamic deletion of objects created on stack. In many cases we may want to delete a pointer but we don’t know whether the pointer is created by Heap or Stack.

e.g. Let’s take a function,

class dummyClass;
void deletePtr(dummyClass * pt)
{
  // Don't know how the pointer is created
  delete pt;
}

In this function we are receiving a pointer and deleting it. But if the passed pointer instead of heap is created on stack then our application will crash. So we have to do add something so that pointer which is created on stack can’t be deleted dynamically.

Restricting the deletion of objects created on stack through delete operator :

We can implement this by counting and marking those objects that are created on heap and marking false for the remaining objects.

When we create object on heap, new operator is called for allocation of memory and after that constructor is called. Then new operator is overloaded and we add mark on new operator in the constructor, if it is true that means current object created on heap.

#include <iostream>
#include <cstdlib>
#include <new>
class dummyClass
{
    static bool lastcallonHeap;
    // Check if current obj created on heap or not
    bool creinheap;
public:
    dummyClass()
    {
        // Set a Heap flag for the current Object
        creinheap = lastcallonHeap;
        // reset the last call flag for new operator
        lastcallonHeap = false;
    }
    static void* operator new(size_t abc)
    {
        std::cout << "operator new is called\n"; // Current Object created on heap
        lastcallonHeap = true; // Call the global new operator
        return ::operator new(abc);
    }
    static void operator delete(void* pt)
    {
        dummyClass * poinPtr = (dummyClass *) (pt);
        // Check if passed object pointer created on stack or not
        if (poinPtr->creinheap)
        {
            ::operator delete(pt);
            std::cout << "deleteion of pointer...successful\n";
        }
        else
            std::cout
                    << "Can't delete...Object may not be allocated from heap\n";
    }
    bool isOnHeap()
    {
        return creinheap;
    }
};
bool dummyClass::lastcallonHeap = false;
int main()
{
    dummyClass poinObj;
    dummyClass * poinPtr2 = &poinObj;
    // Deleting object in stack by delete operator
    delete poinPtr2;
    return 0;
}
Output :
Can't delete...Object may not be allocated from heap