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

后端 未结 5 1326

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:15

    In the first program your variables all reside on the stack. You're not allocating any dynamic memory. 'p' is just sitting on the stack and if you dereference it you'll get garbage. In the second program you're actually creating an integer value on the heap. 'p' is actually pointing to some valid memory in this case. You could actually dereference p and set it to something meaningful safely:

    *p = 5;
    

    That's valid in the second program (before the delete), not the first. Hope that helps.

提交回复
热议问题