When to use heap?

Hi i'm new and i didn't know where else to put this question so forgive me if this isn't the right place. i studied dma (dynamic memory allocation) but it left me with so many questions, one of which is when do we use the free store instead of the stack? a guy told me if i have so many objects i should allocate these objects on the heap so that i wont encounter a stack-overflow but i still dont understand, help me understand better plz.

english is not my native language plz dont use difficult-to-understand words ;) thank you very much.
The advantage to the free store is that the memory you reserve remains available until you explicitly state you are done with it by freeing it. Say you have a game with a level that has 68 enemies, you can allocate the memory for the enemies at the beginning of the lvl and free the memory at the end. You're also allowed to create an object in one function that you can access even after the function ends, unlike in stack where everything you've created in a local scope will be automatically deallocated.

1
2
3
4
int blahblah (int x , int y)
{
return x + y;
}// x and y are local to that function and will vanquish after the function ends - unlike memory on the heap. 


I often try to use automatic variables with references if I need values to be altered by a function just for a little bit of peace of mind.

Most of my use with memory on the heap is for storing data where I don't know what type or size it's going to be at compile time. I can allocate a set amount of memory in bytes using char or in chunks of 4 bytes using int (depending on what I need), for whatever size I find out that I need at runtime.

I believe you also need to use the heap to give access to variables for lots of APIs such as DirectX/OpenGL (I've only really "looked into" graphics a little so far so don't take my word for that)

The rest of what I use the heap for is usually for arrays of unknown size at compile time but known size at runtime. I could use things from the std namespace but strait up dynamic arrays are usually better for what I need.
thank you so much both of you, very helpful
I come again guys :) i don't understand why do people say DMA is more efficient than the stack?
Say you had complex class with so many methods(member functions) and data members. It would be inefficient if you instantiate multiple objects of that class on the stack because it could result in something called a 'stack overflow'. And that happens when the computer no longer has any memory left. So this is where Dynamic memory kicks in and saves the day by allowing the programmer to instantiate those objects out on the heap and gives you the ability to deallocate(free) the memory that's contained on the heap for future use. And that my friend is one of the unique features that makes C++ such a powerful programming language.

Edit: of course these objects would be allocated on the heap so you need a pointer to refer to them :) like this:
Cat* p_Cats = new Cat[1000];
and use (*p_Cats). to use their methods.
or p_Cats -> as well.
Last edited on
ohhhh i see tysm for clarification really helrpfull!
Uk Marine wrote:
And [a stackoverflow] happens when the computer no longer has any memory left

Uh no. A stack overflow happens when the stack pointer reaches past the stack bounds. Your program will very likely not have the entirety of your computer's memory for its stack.

According to your logic, how is using a heap any different than using the stack? If the stack is all your computer's memory, then where does the heap come from?

Please refrain from handing out false information.
Last edited on
so what is the stack? if its not a memory location like uk said then what is it?
Last edited on
The stack is where parameters and local variables are allocated from... the stack refers to a particular portion of the computer's memory. And i don't know what this biscuit person is talking about... Stack overflow happens when all the memory in the stack has been allocated. Stack overflow is generally the result of allocating too many variables on the stack, and/or making too many nested function calls, so it's best to allocate on the heap and then free the memory later on as i've said.
Last edited on
... why do people say DMA is more efficient than the stack

People say a lot of things, the people who are saying this are very confused about their terminology. DMA = "Direct Memory Access", this is feature of a language, specifically it describes the level of control\visibility you have over your variables and their allocation. Maybe they mean that using DMA is more efficient then relying on the stack but A.) it does not matter because much smarter people then you and I developed the part of the compiler that decides which method allocating memory and accessing variables is best; and B.) unless you're writing the ejection system to a fighter jet you'll never notice the fractions of a nano-second it takes a modern PC to calculate the offset from the stack pointer.

To answer your other question, the stack is a portion of memory. Specifically it is the portion of memory that the registers on your CPU use to keep track of certain things that aren't immediately relevant such as the base pointer to the function that called the current one, or locations of memory pages that hold other variables. It does hold some variables itself, but storage is not it's only function. An over simplification would be to say that the stack is the portion of memory that keeps track of the "state" of that specific instance of an applications image in memory.
The stack is an area in memory that is reserved for your program. It's typically pretty small, relative to your total memory.

Uk Marine wrote:
Stack overflow happens when all the memory in the stack has been allocated
Uk Marine wrote:
And [a stackoverflow] happens when the computer no longer has any memory left


These two statements are not equal. At all.

Outside source:
Wikipedia wrote:
In software, a stack overflow occurs when the stack pointer exceeds the stack bound. ... When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow.


Uk Marine wrote:
so it's best to allocate on the heap and then free the memory later on as i've said.

Again, false. It's only best to use the heap if the stack does not work for your purpose. There are many situations where the stack is not suitable, but this does not mean you should blindly use the heap. Allocating memory on the heap is an expensive operation, which can be very error prone.
So, OP, it is best to use the stack unless you actually have to use the heap.

Again, Uk Marine, it is fine to be ignorant of topics. Nobody knows everything. But don't act like you know what you are talking about when you don't. It does nothing but spread false information, confuse newbies, and give us all a bad image.

More sources for OP:
Performance on stack vs heap:
http://stackoverflow.com/a/161061/2887128

Why you should minimize heap usage:
http://stackoverflow.com/q/6500313/2887128

Wikipedia article about memory leaks:
http://en.wikipedia.org/wiki/Memory_leak
Last edited on
Listen, the heap is a large pool of memory.
the stack is not as large as the heap, it's much smaller.
Therefore, large arrays, structures, or classes should be allocated on the heap.
A stack is a last-in, first-out structure. The last item pushed onto the stack will be the first item popped off. Here watch this video you might find it very helpful. https://www.youtube.com/watch?v=_8-ht2AKyH4
Again, Uk Marine, it is fine to be ignorant of topics. Nobody knows everything. But don't act like you know what you are talking about when you don't. It does nothing but spread false information, confuse newbies, and give us all a bad image.

Ok my mistake, sorry.
Edit: i knew what i was talking about, i guess i just didn't explain it correctly but it's ok, i'm not a teacher and this is just a forum.
Last edited on
@ ResidentBiscuit: For the most part I agree with what you've said so far. But you need to quantify this statement here:

Allocating memory on the heap is an expensive operation, which can be very error prone.


Memory allocation is handled by the OS, how can this be "error prone" on a stable release of a modern system? Also it is only potentially expensive, initial page size is a design consideration. You don't page fault with every dynamic allocation. In instances where you expect that this will cause a significant issue you can just tell the OS to give you a whole bunch of RAM ahead of time. Like what std::vector does.
Last edited on
Error prone on the application side, not on the OS side. I guess I should have that more clear.
this is just a forum.


A forum that is often used as a learning resource. If he asked the question, he's probably not clear on the answer. Telling someone the wrong thing here can be just as damaging as a teacher doing it to a student.
Ok i think i understand now, thank you very good people
Topic archived. No new replies allowed.