Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C++ class determine whether it's on the stack or heap?

I have

class Foo { .... } 

Is there a way for Foo to be able to separate out:

function blah() {   Foo foo; // on the stack } 

and

function blah() {   Foo foo* = new Foo(); // on the heap } 

I want Foo to be able to do different things depending on whether it's allocated on the Stack or the Heap.

Edit:

Alof of people have asked me "why do this?"

The answer:

I'm using a ref-counted GC right now. However, I want to have ability to run mark & sweep too. For this, I need to tag a set of "root" pointers -- these are the pointers on the stack. Thus, for each class, I'd like to know whether they're in the stack or in the heap.

like image 384
anon Avatar asked Jan 13 '10 05:01

anon


People also ask

How do I know if my memory is stack or heap?

Stack is a linear data structure whereas Heap is a hierarchical data structure. Stack memory will never become fragmented whereas Heap memory can become fragmented as blocks of memory are first allocated and then freed. Stack accesses local variables only while Heap allows you to access variables globally.

Are C arrays on the stack or heap?

If char charArray[50]; is defined at file scope (outside of all functions) or is static , it's not going to be on the stack, it's going to be a global preallocated at program's start variable. If it's not static and is defined at function scope, it's going to be on the stack.

Does C have stack and heap?

Memory in a C/C++/Java program can either be allocated on a stack or a heap.

Does C use heap memory?

in C, variables are allocated and freed using functions like malloc() and free() the heap is large, and is usually limited by the physical memory available. the heap requires pointers to access it.


1 Answers

A hacky way to do it:

struct Detect {    Detect() {       int i;       check(&i);    }  private:    void check(int *i) {       int j;       if ((i < &j) == ((void*)this < (void*)&j))          std::cout << "Stack" << std::endl;       else          std::cout << "Heap" << std::endl;    } }; 

If the object was created on the stack it must live somewhere in the direction of the outer functions stack variables. The heap usually grows from the other side, so that stack and heap would meet somewhere in the middle.

(There are for sure systems where this wouldn't work)

like image 177
sth Avatar answered Sep 22 '22 13:09

sth