-3

Suppose I want to keep track of all the objects created in a C++ program.

  1. In the stack section of memory (Object obj;)
  2. In heap section of memory (dynamic allocation using new)

Is there any way I can know how many objects are in the stack and how many are in heap memory? The constructor will be called in both cases so it doesn't help.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72
  • 5
    Why did you tag [tag:java] or [tag:oop]? – Max Langhof Nov 12 '19 at 17:30
  • all objects are created in heap (at least for Java) [:-) – user85421 Nov 12 '19 at 17:31
  • 5
    Standard C++ doesn't provide any way to distinguish between objects created on the heap vs stack. An object is not supposed to care. – Jesper Juhl Nov 12 '19 at 17:32
  • @CarlosHeuberger - I don't think that's reliably true if the method has been optimized (by the JVM implementation) and the object doesn't escape the method. But the question repeatedly asks about C++, the Java tag was incorrect, so... :-) – T.J. Crowder Nov 12 '19 at 17:32
  • 5
    Sounds like an XY problem. Please, describe what you're trying to achieve. – ProXicT Nov 12 '19 at 17:39
  • For platforms implementing a stack, temporary variables are placed on the stack and removed when they go out of scope. How many objects on this stack depends on a time snapshot, i.e. where in the function the execution is. Also, temporary variables may also be allocated in registers rather than a stack. – Thomas Matthews Nov 12 '19 at 19:11
  • What about automatic memory area? This is where static and global variables are allocated. – Thomas Matthews Nov 12 '19 at 19:13

1 Answers1

2

See: What and where are the stack and heap?

In particular:

"The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application."

and...

...while the stack is allocated by the OS when the process starts (assuming the existence of an OS), it is maintained inline by the program. This is another reason the stack is faster, as well - push and pop operations are typically one machine instruction, and modern machines can do at least 3 of them in one cycle, whereas allocating or freeing heap involves calling into OS code.

Thus, I believe the answer to your question is that you'd need full root access to the operating system's internal memory paging system to keep track of all objects (particularly on the heap). As far as I know, all garbage collection systems use a reference count approach to manage heap memory allocation and don't directly access the operating system's heap allocation records. There are very good security reasons for this I'm sure.

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11