How does automatic memory allocation actually work in C++?

后端 未结 5 1314

In C++, assuming no optimization, do the following two programs end up with the same memory allocation machine code?

int main()
{     
    int i;
    int *p;         


        
5条回答
  •  时光说笑
    2020-12-09 00:13

        int i;
        int *p;
    

    ^ Allocation of one integer and one integer pointer on stack

    int *p = new int;
    delete p;
    

    ^ Allocation of one integer pointer on stack and block of the size of integer on heap

    EDIT:

    Difference between Stack segment and Heap segment


    (source: maxi-pedia.com)

    void another_function(){
       int var1_in_other_function;   /* Stack- main-y-sr-another_function-var1_in_other_function */
       int var2_in_other_function;/* Stack- main-y-sr-another_function-var1_in_other_function-var2_in_other_function */
    }
    int main() {                     /* Stack- main */
       int y;                        /* Stack- main-y */
       char str;                     /* Stack- main-y-sr */
       another_function();           /*Stack- main-y-sr-another_function*/
       return 1 ;                    /* Stack- main-y-sr */ //stack will be empty after this statement                        
    }
    

    Whenever any program starts executing it stores all of its variables in special memoy memory location called Stack segment. For example in case of C/C++ first function called is main. so it will be put on the stack first. Any variables inside main will be put on stack as program executes. Now as main is the first function called it will be last function to return any value (Or will be popped from stack).

    Now when you dynamically allocate memory using new another special memory location is used called Heap segment. Even if actual data is present on heap pointer lies on stack.

提交回复
热议问题