c++ - 内存布局练习 C++

标签 c++ memory-layout

我正在阅读 B.Stroustrup 的“使用 C++ 的编程原则和实践”,并且我正在尝试完成大部分练习。这个非常有趣,我不知道从哪里开始。

练习是:

Consider the layout in 17.4. Write a program that tells the order in which static storage, the stack, and the free store are laid out in memory. In which direction does the stack grow : upward toward higher addresses or downward toward lower addresses?

17.4 中的布局:

Code - memory for code

Static data - space for global variables

Free store - available memory

Stack - memory for calling functions and space for their arguments and local variables

我怎么才能真正知道这一切发生的顺序?更好的是,我如何实际输出它发生时发生的顺序?

它不是应该由编译器处理,还是我只是误解了这个练习?一些小技巧真的很酷!

谢谢

最佳答案

Isn't it supposed to be handled by compiler

链接器,更具体地说。

这是一个起点,完全按照 Joseph Mansfield 的建议进行。

#include <iostream>

int static_data;

int main()
{
    int stack_data;

    if ( &static_data < &stack_data )
    {
        std::cout << "Static data is in lower memory than the stack.";
    }
}

关于c++ - 内存布局练习 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29438702/

相关文章:

c++ - QT creator和Designer的区别——起步QT

c++ - 使用 ifstream 从文本文件中读取

c++ - 是否有不关心结构/类布局的编译指示?如果不是,为什么?

c++ - 将 3 个整数的结构 vector 解释为数组

c++ - 当基类具有虚函数时,对基类的静态转换会产生意想不到的结果

c++ - C++11 中类型的逐字节拷贝?

java - 游戏开发 : How to limit FPS?

C++ 指向对象的类成员的指针

c++ - 根据C++标准的多态对象的存储布局

swift - 在 Swift 3 中从数据初始化结构