c++ - 如何为局部变量分配内存?

标签 c++ c memory-leaks memory-management

int* pi;
{
    int ar[1000000];
    int a =3,b=4;
    ar[3]=a*b
    pi=ar;
}//ar is destroyed
int ar2[]={5,6,7,8,9};
char* f="zcxzsdaaaaaaaaa";
std::cout<<pi[3]<<std::endl;// prints 12

我有两个问题:

  1. 我听说堆栈只包含指向数据的指针。如果是这样,数据存储在哪里?例如 char* a="bbbb"; a - 放在堆栈上,"bbbb"- 其他地方。在哪里?

  2. 上面的代码运行正常不是意味着 1000000 字节的内存泄漏吗?变量 ar 被销毁,但它指向的数据仍然存在。我们不能在这里使用 delete,因为 ar 不是动态分配的。

最佳答案

I heard that stack contain only pointers to data

你听错了。堆栈包含实际数据。但是,如果该数据是一个指针,那么它就是存储的内容。

And if so where is data stored? For example char* a="bbbb"; a - placed on stack, "bbbb" - somewhere else. Where?

是的,a(指针)存储在堆栈中。实际字符串 "bbbb" 存储在可执行文件的固定部分。

Doesnt code above working correctly mean memory leak of 1000000 bytes? Variable ar is destroyed but data that it pointed to still exists. And we cant use delete here since ar is not dynamically allocated.

不,数组和指向数组的指针是有区别的。 ar(整个 1000000 字节)将存储在堆栈中。这不同于 char const* ar = "... 1000000 chars ...";。由于 ar 在堆栈上,它会自动“释放”。

char const* a = "abcde"; // a is on the stack, pointing to "abcde" somewhere else.
char const b[6] = "abcde"; // *all* of b is on the stack, all 6 bytes

您的代码中的问题是 pi 指向堆栈上不再存在的内容。当您运行代码时,它很可能就在那里,因为“释放”堆栈上的数据不会对非调试构建中的数据做任何事情。这不是内存泄漏,您只是有一个无效的指针。

最后说明:尽管基本上所有现代计算机体系结构都使用调用堆栈,但 C++ 标准并未提及它。请注意,人们经常会说变量“在堆栈上”,但实际上它可能只是存在于寄存器中。例如,如果你编译你的代码,变量 pi 可能永远不会接触堆栈,它可能只会在函数执行期间停留在寄存器中,因为进入堆栈的成本相对较高(与寄存器相比)。

关于c++ - 如何为局部变量分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614131/

相关文章:

c - 快速读取文件

objective-c - NSEvent addLocalMonitorForEventsMatchingMask 内存泄漏

c - 如何释放 g_thread_init 分配的内存

c++ - 我的文件链接到 libGL.so.1

c++ - 使用 Qt 和 QSortFilterProxyModel 实现不同的 View

c++ - 外部 IP 地址

c - c中的两个函数使用相同的指针

c - 函数什么时候必须通过引用接收参数才能改变参数的某些内容?

iphone - 分配属性(property)

c++ - 二维数组加法