Identify on what region the object is created

Using C++ we will identify the memory region of an object by declaring a new variable and compare this variable from the object that we wanted to identify. If the address of an object is in close proximity to the new variable then they are in the same region. This solution is accurate only for non multi threaded system or large project as I only assume 1000 bytes or 250 pointer variables gap from the new variable to the object we are comparing.

class ObjectDiagnostic {
public:
   static int obj_alive;
   ObjectDiagnostic(string name) {
      ++obj_alive;
      std::cout << "Name: " << name << " located in " << getMemLocation() << std::endl;
   }
   const char* getMemLocation() {
        int* p = new int(1); //heap variable
        const char* memAlloc = "HEAP";
        if (((&p - (void*)this) * -1) < 1000) {
            memAlloc = "STACK";
        }
        return memAlloc;
   }
}

int main() {
    ObjectDiagnostic() objD = ObjectDiagnostic("objD"); //stack object
    ObjectDiagnostic() *objD2 = new ObjectDiagnostic("objD2"); //heap object
}

The most accurate one is to use the assembly and access the current stack pointer.

asm("mov %%rsp, %0" : "=rm" (stackpointer))

and use that as the reference rather than declaring a variable as reference.

C/C++