0

So currently I've been working with pointers and now I know how to use them and where are they going in the money, but there is still one question that keeps bothering me. Why do I want some things in Heap and some in Stack ?

When we are declaring a pointer the variable and the address stays in the stack, but the specific pointer address POINTS to the value. Okay, but why do I want to do that ? Why shouldn't I just declare a normal variable ? What's the point and when do I have to use dynamic memory allocation ?

trincot
  • 317,000
  • 35
  • 244
  • 286

2 Answers2

0

Heap memory 'lives' until you call delete (or delete[]), stack memory only lives until you exit the scope in which it is declared. That's the difference.

john
  • 85,011
  • 4
  • 57
  • 81
  • Okay, so the purpose is that I could deallocate the memory before the out of scope, which is faster ? – Ивелин Иванов Jun 20 '20 at 13:14
  • No, the point is that you don't have to deallocate the memory when it goes out of scope. – john Jun 20 '20 at 13:23
  • Stack allocation is faster. – john Jun 20 '20 at 13:24
  • 1
    Heap allocated memory does not automatically get deallocated in any circumstances. Even when a pointer pointing at the memory goes out of scope the memory remains allocated. You decide (by calling delete) when the memory gets deallocated. – john Jun 20 '20 at 13:27
  • The stack is also typically very small by default while the heap is large and can be larger than the amount of physical ram you have on an OS that uses virtual memory. On Visual Studio the default stack size is 1MB other compilers may have a default that is up to 10 times that. – drescherjm Jun 20 '20 at 13:31
  • An example of heap memory is values and variables initiated in the global scope. An example of stack memory is the `std::unique_ptr` or `shared_ptr` classes located in `` – Skiller Dz Jun 20 '20 at 13:47
  • This comment is just for giving an example, nothing else. – Skiller Dz Jun 20 '20 at 13:48
0

Well, it all depends on you and your application.

Use of Stack You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.

Use of Heap: You would use the heap if you don't know exactly how much data you will need at run time or if you need to allocate a lot of data.

you can also refer below link more detail

What and where are the stack and heap?

Nilesh Solanki
  • 336
  • 4
  • 19