stack vs heap

Started by
30 comments, last by King Mir 11 years, 1 month ago

Hello.

I'm working as java programmer and just now starting to learn c++ and irrlicht (want to create games as a hobby ;) ).

I am completely confused by stack vs heap issue.

What is the advantage of using heap? Isn't it MUCH faster and more efficient to create variales on stack and pass them by reference.

What I mean is:

Object obj = new Object();

VERSUS

Object obj;

method1(&obj)

I am also confused by memory managment in c++. When stack object is freed is there a memory "hall" in stack.

Thanks

Advertisement
Yes, you should use automatic (stack) lifetimes where possible, and heap lifetimes where you have to.
n.b. with your example of using new, it returns a pointer to an object (in Java, every "object"-type variable is implicitly a pointer, but in C++ you need the "*")
{
Object* obj1 = new Object();//obj1 is a local variable, that is a pointer to a heap allocated object
Object& obj2 = *(new Object()); //a reference is pretty much the same thing as a pointer, but looks like it isn't ;)
Object obj3;//local variable (stack allocation)
delete obj1;
delete &obj2;
delete &obj3;//this is an error! It wasn't made with 'new' so you can't use 'delete'
}//obj3 deleted here automatically due to the stack unwinding

I am also confused by memory managment in c++. When stack object is freed is there a memory "hall" in stack.

You can't manually "free" an object from the stack. Stack frames are pushed and popped for each "block" of code (basically every set of "{ ... }"). Whenever a "}" is reached, all the stack variables that were created in that block are destroyed. So there are never any holes.

For an example of where stack allocation isn't applicable, imagine a function that makes a new monster appear:
Monster* SpawnMonster()
{
  Monster m;
  return &m;//error! m is created with the same scope as this function. When the function returns, m is "deleted".
}
 
Monster* SpawnMonster()
{
  Monster* m = new Monster();
  return m;//correct, but someone has to delete this at some point, otherwise you've got a memory leak
}
shared_ptr<Monster> SpawnMonster()
{
  return shared_ptr<Monster>(new Monster());//also correct. This acts more like what you're used to in Java. When there are no more shared_ptr's that reference the Monster, it will automatically be deleted.
}

Hello.

I'm working as java programmer and just now starting to learn c++ and irrlicht (want to create games as a hobby ;) ).

I am completely confused by stack vs heap issue.

What is the advantage of using heap? Isn't it MUCH faster and more efficient to create variales on stack and pass them by reference.

What I mean is:

Object obj = new Object();

VERSUS

Object obj;

method1(&obj)

I am also confused by memory managment in c++. When stack object is freed is there a memory "hall" in stack.

Thanks

Generally in C++ if you want by reference passing of variables you define this in the function header not in it's use.


void functionByReference(const Object& obj);
void functionByPointer(const Object* obj); //In compiled code(asm) there is no difference between this call and the one above it, the compiler does see this differently though.
void functionByValue(const Object obj);
 
//Both are called as follows
Object object;
functionByReference(object); //This call is faster then the one below it
functionByValue(object);
 
functionByPointer(&object); //You have to use the address operator here because the function is expecting a pointer to an object

Usually you only feed a function a "&<variable>" when you only have a stack value and the function wants a object that's passed by pointer. Even when the variable is an output parameter this is expressed in the function header and not in it's use.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

The language in NightCreature83's post is not completely clear, so let me clarify. There is no notion of "function header": He probably meant to say "function prototype".

C++ has no notion of output parameter. If you want to use a parameter for output, you can make it a reference or a pointer. If you make it a reference, the code that calls the function will be indistinguishable from passing by value or by `const' reference. If you made it a pointer, the code would look just the way the OP posted (with the `&'). That's why I usually prefer to get a pointer for variables I intend to modify.

Another place you will often want heap allocation is when you are using polymorphism.

OK biggrin.png Now it's MUCH clearer.

As I see it now, I should use stack vars if and only if it's life span does NOT need to exceed the scope of it's creation {}.

Also, a "little" advantage of heap vars is that I can free them in the "middle" of the scope, thus the memory usage is a little smaller.

Ok! I will use stack vars where I can !

Thank you all for the valuable answers :)

Furthermore, stack memory should be avoided when dealing with large sets of data since most operating systems gives a limit for stack allocation (something in the order of 10mb from my experience), so if you try to declare an data array of size bigger than 10mb for example, your program will most likely crash.

Thought it would be worth mentioning since it's a bug very difficult to catch. I don't know what are the workarounds for that so I only use heap for large data allocation.

Tiago.MWeb Developer - Aspiring CG Programmer

Furthermore, stack memory should be avoided when dealing with large sets of data since most operating systems gives a limit for stack allocation (something in the order of 10mb from my experience), so if you try to declare an data array of size bigger than 10mb for example, your program will most likely crash.

Thought it would be worth mentioning since it's a bug very difficult to catch. I don't know what are the workarounds for that so I only use heap for large data allocation.

0.o are you sure about this one? In java, for example, I do sometimes have objects of this size. When I work with images, pdfs...

So I should create objects on stack only if their size < X ???

Furthermore, stack memory should be avoided when dealing with large sets of data since most operating systems gives a limit for stack allocation (something in the order of 10mb from my experience), so if you try to declare an data array of size bigger than 10mb for example, your program will most likely crash.

Thought it would be worth mentioning since it's a bug very difficult to catch. I don't know what are the workarounds for that so I only use heap for large data allocation.

0.o are you sure about this one? In java, for example, I do sometimes have objects of this size. When I work with images, pdfs...

Java isn't allocating that memory on the stack. It's allocating it on the heap.

So I should create objects on stack only if their size < X ???

If you are dealing with large objects (like large arrays), you should allocate them on the heap. Besides, I've typically found that if I need a (potentially) large array, it's probably a dynamically sized array too, so allocating it on the stack at compile time makes very little sense.

[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

You can test it yourself, start by declaring a small vector and keep increasing it's size.

float hum[100000];

float hum[1000000];

float hum[10000000];

Eventually you'll reach a "segmentation fault" error.

I can't ensure you of this fact, since I could have done some wrong compiler configuration or my O.S (Ubuntu) deals with memory management in a different way, so I'll leave to more experienced programmers to elaborate on this. I had this issue once and it was very hard to figure it out.

Let me know what yo find.

Tiago.MWeb Developer - Aspiring CG Programmer

This topic is closed to new replies.

Advertisement