When are variables removed from memory in C++?

前端 未结 11 1136
梦如初夏
梦如初夏 2020-12-16 06:54

I\'ve been using C++ for a bit now. I\'m just never sure how the memory management works, so here it goes:

I\'m first of all unsure how memory is unallocated in a fu

11条回答
  •  天涯浪人
    2020-12-16 07:21

    Here, temp is allocated on the stack, and the memory that it uses is automatically freed when the function exits. However, you could allocate it on the heap like this:

    int *temp = new int(2);
    

    To free it, you have to do

    delete temp;
    

    If you allocate your variable on the stack, this is what typically happens:

    When you call your function, it will increment this thing called the 'stack pointer' -- a number saying which addresses in memory are to be 'protected' for use by its local variables. When the function returns, it will decrement the stack pointer to its original value. Nothing is actually done to the variables you've allocated in that function, except that the memory they reside in is no longer 'protected' -- anything else can (and eventually will) overwrite them. So you're not supposed to access them any longer.

    If you need the memory allocated to persist after you've exited the function, then use the heap.

提交回复
热议问题