为什么此指针包含存储在堆上的地址
Why does this pointer contain an address stored on the heap?
这是我的代码(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[];
在看到此程序的输出之前,我希望a
,b
和c
在堆栈上包含地址,而d
堆上的地址。但是,输出看起来像这样:
0x7fff5a5ea38e:a
0x7fff5a5ea38c:b
0x105616f7c:c
0x7fa01bc02690:d
由于堆栈指针从最高地址生长,并且从最低的地址向上堆指针,因此a
,b
和d
似乎存储在堆栈上,而c
则存储在堆上。是这样吗?
我的问题是,为什么c
存储在堆上是有意义的,因为我没有用new
关键字分配内存?这是否意味着c
的初始化创造了内存渗漏?为什么d
存储在堆栈上,因为我专门分配了内存?
谢谢!
您对内存区域的猜测不是很准确。a
和b
确实在堆栈上生活,因为它们是数组。但是,c
是一个指向字符串文字的指针,该指针存储在二进制图像中的.rodata
部分中(既不是堆栈也不是堆)。d
的值为380&nbsp; gb(!),小于a
和b
;它在堆上(这是一个单独的内存区域,尽管不是任何"最低地址")。
请记住,除了与语言无关的平台特定细节外,诸如ASLR之类的东西使这种观众运动变得困难。
相关文章:
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 是否可以仅通过将分配的指针地址存储在C++中来分析内存?
- 为什么存储在数组中的地址值与其自己的地址相同,它应该指向某个不同的地址(&arr[0])?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 存储 std::list 元素的地址;内存
- 为什么这段代码给出错误......'a'是指针到字符指针,应该存储's'的地址,因为s是指向数组的第一个元素的指针
- 如何反转存储在内存地址的位?
- 为什么类型转换对象不会更改其地址?有关对象类型的信息存储在哪里?
- 为什么存储对象地址在缓冲区中会导致内存泄漏并删除它们
- 相同的地址存储在链表的头部
- 可以读/写EEPROM地址,但是只能读/写第一个存储页面
- 整数必须存储在连续的内存地址中吗?
- 如何将内存地址存储在整数中?
- 可以将内存地址存储为整数类型
- 将地址存储到矢量中的堆栈分配对象
- 局部变量和其他变量类型的地址存储在哪里
- 将缓冲区的地址存储为无符号整数;
- 将地址存储为字符串
- 将指针的内存地址存储为整数
- 将字符的地址存储到整数指针