c++ - 为什么malloc()返回高位地址?

标签 c++ macos

我有一个源文件:

#include <cstdlib>
#include <iostream>

int main() {
    void *p = std::malloc(8192);
    std::cout << std::hex << (size_t)p << std::endl;
    std::free(p);
}

我在两个平台上对其进行了编译:(a)在MacOS上使用clang++ 4.2.1,以及(b)在Linux上使用g++ 7.3.0。

在macOS上,打印输出为7fa432001000,在Linux上为257ec20

无法预期macOS的打印输出。我认为malloc()应该在堆中分配内存,如果它在后台使用mmap()分配内存,那也很好。但是7fa432001000 似乎在堆栈位置中的一个地址,因为x86_64上虚拟内存的上限刚好低于7fffffffffff(至少在当前的Linux中是这种情况-也许我错了)。

我的问题是:为什么(或如何)macOS上的malloc()返回这么高的地址?这是因为实现了Clang的libc++的方式吗?

最佳答案

这是由于现代系统将虚拟地址映射到实际物理地址。

根据Wikipedia:

The computer's operating system, using a combination of hardware and software, maps memory addresses used by a program, called virtual addresses, into physical addresses in computer memory. Main storage, as seen by a process or task, appears as a contiguous address space or collection of contiguous segments. The operating system manages virtual address spaces and the assignment of real memory to virtual memory. Address translation hardware in the CPU, often referred to as a memory management unit or MMU, automatically translates virtual addresses to physical addresses. Software within the operating system may extend these capabilities to provide a virtual address space that can exceed the capacity of real memory and thus reference more memory than is physically present in the computer.



至于为什么它在两个不同的平台上不同,那是因为不同的计算机硬件以不同的方式处理内存。 BIOS和其他固件可能具有不同的算法或技术;不同的OS或OS版本执行不同的操作(构建内核时Linux具有不同的选项); C++运行时的实现方式可能有所不同。

关于c++ - 为什么malloc()返回高位地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52325264/

相关文章:

c++ - 类 C、构造函数和统一初始化之间有什么区别?

java - 我应该为 Mac/Windows Java 应用程序使用什么打包工具?

macos - 安装了 thrift 但是当尝试运行 thrift 命令时它说 Thrift : command not found

java - 在 Mac 上启动时,Swing GUI 不显示或显示错误

python - 删除 python 然后在 Mac OSX 上重新安装

c++ - 使数据成员随处可访问,但只读

c++ - 迭代器边界检查超出 vector 大小

c++ - 为科学代码选择前端/解释器

c++ - 重构 C++ 代码以使用前向声明

java - 错误: Could not find or load main class Mac Eclipse