简体   繁体   中英

c++ memory management memory allocation on local variables

In the following code I allocate many times an array of integers to a pointer. In each call the address of the of the pointer is the same, at least when I run it. If I do not use the delete [] y the process will be killed without any exception being thrown. If I add the line the process runs for ever.

My question is, since in both cases (using or not using delete ) the address of the pointer remains the same between the calls of the function, does this mean that the same space in memory is allocated? If yes why in one case the process is halted and in the other not?

In a more general question, what happens to the memory used for local variables when a function returns? Is memory management strategy different between regular variables and pointers?

#include<cstdio>
#include<iostream>
#include<exception>
#include<new>

using namespace std;

void foo();

int main()
{
    while(true)
    foo();   
}

void foo()
{
     try{
           int *y=new int[1000];
           printf("%X\n",&y);
           // delete []  y;
      }
     catch(exception &exc){
           cerr<< exc.what();
      }

}

You are printing the address of the pointer variable, not the address of the allocated area. Try this to see the address of the allocated area:

printf("%p\n", (void*)y);

If you delete the pointer, then you may get the same value from new in each call. If you don't delete the pointer, then you will never get the same pointer returned, as the function have to allocate new memory and the system can't reuse some previously deleted memory.

And memory you allocate dynamically stays allocated for the remainder of the process, it's not "local" in the same sense that variables can be local. If you do not free (by using delete ) the memory then you have a memory leak.

函数返回时用于局部变量的内存将由下一个函数调用和该下一个函数的局部变量重用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM