Restrict dynamic deletion of objects created on stack

Many times we encounter a situation where we need to delete a pointer but we are not sure that how this pointer is created i.e. either on Heap or on stack.

Check out this function,

C++

1

2

3

4

5

6

7

8

classDummy;

voiddeletePointer(Dummy*ptr)

{

// Do you know this passed pointer was

// created on heap or stack ???

delete ptr;

}

In this it’s receiving a pointer and deleting it. But wait a minute….

What is this passed pointer is created on stack instead of heap ?
i.e.

C++

1

2

3

4

Dummy obj;

Dummy*dPtr=&obj;

deletePointer(dPtr);

BOOM………….
In this type of case our application will crash.

Can we do something about it? Can we add a restriction in my class, so that pointer of object created on Stack can not be deleted dynamically i.e. by delete operator?

Yes we can do this.

Adding restriction on deletion of objects created on stack through delete operator

Mark each object created on heap and for other objects this marking will return false.

For this we will require following items in our class

Each Object will contain a member variable that will tell that current object is created on heap or not.

A static member variable in class that we will set in new operator and constructor

How This will work,

Each time we create an object on heap first operator new is called to allocate the memory and then its constructor is called. So, overload the new operator and add mark that new operator is called. Then in constructor check if new opeartor mark is true it means the current object is created on heap, so just update a member variable i.e. Heap marking for this current object. Afterwards reset the new operator Mask.

Now we have a member function that can tell if current object is created on heap or not.

Now overload the delete operator and before calling global operator on passed pointer check if it was created on heap or not.

Checkout following example.

C++

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

#include <iostream>

#include <cstdlib>

#include <new>

classDummy

{

// Track the last call of new operator

staticboolm_islastCallOnHeap;

// Tells if current object is created on

// Heap or not

boolm_isOnHeap;

public:

Dummy()

{

// Set the Heap flag for current Object

m_isOnHeap=m_islastCallOnHeap;

// reset the last call mark of new operator

m_islastCallOnHeap=false;

}

staticvoid*operatornew(size_t sz)

{

std::cout<<"operator new called\n";// Current Object will be created on heap