为什么此指针包含存储在堆上的地址

Why does this pointer contain an address stored on the heap?

本文关键字:地址 存储 指针 包含 为什么      更新时间:2023-10-16

这是我的代码(Mac OS上的g++编译器):

/* initialize character arrays */
char a[2] = "a";
char b[2] = "b";
/* assigns to c the pointer to a read-only buffer containing 'c' */
char* c = "c"; // does this cause a memory leak?
/* allocate heap-memory for d */
char* d = new char[2];
strcpy(d, "d");
/* print addresses and values */
std::cout << (void*)a << ":" << a << 'n';
std::cout << (void*)b << ":" << b << 'n';
std::cout << (void*)c << ":" << c << 'n';
std::cout << (void*)d << ":" << d << 'n';
/* free memory */
delete d[];

在看到此程序的输出之前,我希望abc在堆栈上包含地址,而d堆上的地址。但是,输出看起来像这样:

0x7fff5a5ea38e:a
0x7fff5a5ea38c:b
0x105616f7c:c
0x7fa01bc02690:d

由于堆栈指针从最高地址生长,并且从最低的地址向上堆指针,因此abd似乎存储在堆栈上,而c则存储在堆上。是这样吗?

我的问题是,为什么c存储在堆上是有意义的,因为我没有用new关键字分配内存?这是否意味着c的初始化创造了内存渗漏?为什么d存储在堆栈上,因为我专门分配了内存?

谢谢!

您对内存区域的猜测不是很准确。ab确实在堆栈上生活,因为它们是数组。但是,c是一个指向字符串文字的指针,该指针存储在二进制图像中的.rodata部分中(既不是堆栈也不是堆)。d的值为380&nbsp; gb(!),小于ab;它在堆上(这是一个单独的内存区域,尽管不是任何"最低地址")。

请记住,除了与语言无关的平台特定细节外,诸如ASLR之类的东西使这种观众运动变得困难。