C++函数内存对齐

标签 c++ memory

我以前读过类似的东西,但不幸的是,忘记了一些细节。

请解释函数内存对齐:

int f(int a = 3, int b = 5) {
    int c = 7;

    int *p = &c;

    std::cout << "Pointer value: " << *p << "\tPointer address: " << p  << std::endl;
    --p;
    std::cout << "Pointer value: " << *p << "\tPointer address: " << p  << std::endl;
    --p;
    std::cout << "Pointer value: " << *p << "\tPointer address: " << p  << std::endl;
    --p;
    std::cout << "Pointer value: " << *p << "\tPointer address: " << p  << std::endl;
    --p;
    std::cout << "Pointer value: " << *p << "\tPointer address: " << p  << std::endl;
    --p;
    std::cout << "Pointer value: " << *p << "\tPointer address: " << p  << std::endl;

    std::cout << "A address: " << &a  << std::endl;
    std::cout << "B address: " << &b  << std::endl;

    return c;
}

产生输出:

Pointer value: 7        Pointer address: 0x7ffd62ee8dcc
Pointer value: 6299840  Pointer address: 0x7ffd62ee8dc8
Pointer value: 32748    Pointer address: 0x7ffd62ee8dc4
Pointer value: -2112316480      Pointer address: 0x7ffd62ee8dc0
Pointer value: 3        Pointer address: 0x7ffd62ee8dbc
Pointer value: 5        Pointer address: 0x7ffd62ee8db8
Actual A address: 0x7ffd62ee8dbc
Actual B address: 0x7ffd62ee8db8

什么位于函数参数和堆栈中的第一个对象之间?

最佳答案

极好的好奇心。您会发现调用函数时实际发生了什么,这是非常宝贵的信息。

堆栈不仅仅用于存储局部变量和函数参数。堆栈内容的确切布局由 ABI 决定,ABI 是对如何调用函数的特定于体系结构的描述。因此,在不知道这段代码是为什么架构编写的情况下,我无法提供具体细节。但一般来说,这些可能是调用函数时 CPU 的某些寄存器的值。该函数需要使用其中一些寄存器来完成其工作,因此它将它们的值保存在堆栈中,稍后它将在返回调用函数之前将这些值返回到它们在寄存器中的原始位置(调用函数还将地址压入返回到堆栈上)。

一个很好的下一步是向您的编译器传递正确的标志,使其在生成程序集之后但在汇编生成的目标文件和可执行文件之前停止。

关于C++函数内存对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30512995/

相关文章:

c++ - 从文件中读取浮点值会删除全部或部分小数部分

c - 全局内存状态Ex() (Win32)

ios - react-native ios,如何在内存不足的情况下从缓存中释放本地镜像?

c++ - 如何在c++中使用虚类调用其他类的方法?

python - Swig 包装一个 C++ 数据类型?

c++ - 遇到 C++ 代码 "#define ELEMENT(TYPE, FIELD)"

c++ - 我应该为索引变量使用什么类型

memory - 在 Fortran 90 中跟踪内存使用情况

memory - 如何访问内核中的常量内存?

c++ - 在 C++ 中玩转内存