Detecting pointer target: static memory or dynamic memory?

207 views Asked by At

Is there functionality, in C++, to detect whether the target of a pointer has been allocated from dynamic memory or is living in static memory (including global memory)?

In the example below, I'd like to have the Destruction function only call delete if the target of the pointer resides in dynamic memory. (This is a minimized version of the actual code.)

#include <iostream>
using std::cout;

void Destruction(int * p_variable)
{
    // The statement below should only be executed
    //    if p_variable points to an object in dynamic memory.
    delete p_variable;
}

int main()
{
    cout << "Deletion test.\n";
    static int static_integer = 5;
    int * p_dynamic_integer = new int;
    *p_dynamic_integer = 42;

    // This call will pass
    Destruction(p_dynamic_integer);

    int * p_static_integer = &static_integer;
    // Undefined behavior???
    Destruction(p_static_integer);

    cout << "\nPaused.  Press Enter to continue.\n";
    cout.ignore(10000, '\n');
    return 0;
}

The basis of the question is that I'm getting an exception error in the Destruction function because the pointer is pointing to a static integer.

The design is that a Factory Pattern function returns a pointer to a base class. The pointer could be pointing to a child that is a singleton (static memory) or an child instance from dynamic memory. A function is called to close the program (think closure of a GUI) and if the target of the pointer is from dynamic memory, it needs to be deleted.

I'm looking for a solution where I don't have to worry about deleting or not deleting the target of the pointer.

1

There are 1 answers

0
Secundi On

As far as I know, there's at least no clean/robust way to do that. Maybe there are some further heuristic approaches/hacks like the ones here:

static and dynamic memory allocation of objects in C++

But as another user already mentioned there: If you really have to distinguish the memory place type, which might be questioned in terms of design at least (there are dozends of singleton concepts that cover some of the aspects here), you could provide this information explicitly for the used class.