Stack, Static, and Heap in C++

前端 未结 9 2085
温柔的废话
温柔的废话 2020-11-22 05:17

I\'ve searched, but I\'ve not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what\'s its real advantage? What are the

9条回答
  •  迷失自我
    2020-11-22 05:31

    I'm sure one of the pedants will come up with a better answer shortly, but the main difference is speed and size.

    Stack

    Dramatically faster to allocate. It is done in O(1) since it is allocated when setting up the stack frame so it is essentially free. The drawback is that if you run out of stack space you are boned. You can adjust the stack size, but IIRC you have ~2MB to play with. Also, as soon as you exit the function everything on the stack is cleared. So it can be problematic to refer to it later. (Pointers to stack allocated objects leads to bugs.)

    Heap

    Dramatically slower to allocate. But you have GB to play with, and point to.

    Garbage Collector

    The garbage collector is some code that runs in the background and frees memory. When you allocate memory on the heap it is very easy to forget to free it, which is known as a memory leak. Over time, the memory your application consumes grows and grows until it crashes. Having a garbage collector periodically free the memory you no longer need helps eliminate this class of bugs. Of course this comes at a price, as the garbage collector slows things down.

提交回复
热议问题