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("%Xn",&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("%pn", (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.
当函数返回时用于局部变量的内存被下一个函数调用和下一个函数的局部变量重用。
链接地址: http://www.djcxy.com/p/36342.html上一篇: 在这个memcpy实现中最佳?
下一篇: 本地变量的c ++内存管理内存分配