简体   繁体   English

C ++内存管理在局部变量上的内存分配

[英]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. 如果我不使用delete [] y该进程将被杀死,而不会引发任何异常。 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? 我的问题是,由于在两种情况下(使用或不使用delete ),在函数调用之间指针的地址都保持不变,这是否意味着在内存中分配了相同的空间? 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. 如果delete指针,则每个调用中的new值都可能相同。 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. 如果不delete指针,则将永远不会返回相同的指针,因为该函数必须分配新的内存,并且系统无法重用某些先前删除的内存。

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. 如果您没有释放内存(通过使用delete ),则内存泄漏。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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