Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it best to use the stack instead of the heap and vice versa?

Tags:

c++

In C++, when is it best to use the stack? When is it best to use the heap?

like image 296
Anthony Glyadchenko Avatar asked Sep 19 '08 13:09

Anthony Glyadchenko


People also ask

Is it better to use stack or heap?

Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread. Memory allocation and de-allocation is faster as compared to Heap-memory allocation. Stack-memory has less storage space as compared to Heap-memory.

Why is heap more preferred in working memory?

The best reason for heap allocation is that you cant always know how much space you need. You often only know this once the program is running. You might have an idea of limits but you would only want to use the exact amount of space required.

What is the difference between stack and heap overflows?

There are two main types of buffer overflows: stack overflows and heap overflows. Stack overflows corrupt memory on the stack. This means that values of local variables, function arguments, and return addresses are affected. Whereas heap overflows refer to overflows that corrupt memory located on the heap.

When should I allocate on the heap?

If you need to control manually the lifetime of the object, allocate it on the heap. If the object is big and the stack is not big enough for it, allocate it on the heap.


2 Answers

Use the stack when your variable will not be used after the current function returns. Use the heap when the data in the variable is needed beyond the lifetime of the current function.

like image 197
Eddie Deyo Avatar answered Sep 27 '22 20:09

Eddie Deyo


As a rule of thumb, avoid creating huge objects on the stack.

  • Creating an object on the stack frees you from the burden of remembering to cleanup(read delete) the object. But creating too many objects on the stack will increase the chances of stack overflow.
  • If you use heap for the object, you get the as much memory the OS can provide, much larger than the stack, but then again you must make sure to free the memory when you are done. Also, creating too many objects too frequently in the heap will tend to fragment the memory, which in turn will affect the performance of your application.
like image 32
nullDev Avatar answered Sep 27 '22 20:09

nullDev