c++对象的成员变量在进程内存中的存放位置

一个典型的进程地址空间:

这里写图片描述

对于我们自定义类型对象的成员变量来说,它在进程运行时,应该储存在哪里??Data区?堆区??栈区??

我们猜想它在栈区,现在来验证一下。 先写如下代码:

#include<iostream>
#include<unistd.h>
using namespace std;
int s2=0;
class cal
{
  public:
       void s(){};
       int s1;

};
int s3;
int main()
{
  void *t,*t1;
  t1=sbrk(0);
  cout<<t1<<endl;
  cal c;
  t=sbrk(0);
  cout<<&s2<<endl;
  cout<<&s3<<endl;
  cout<<&c.s1<<endl;
  cout<<t<<endl;
}

运行结果:

这里写图片描述

我们发现cal 对象声明前后,sbrk()返回的值没有变化(sbrk()用于返回程序间断点),说明声明对象后,堆区无变化。而且c.s1的地址远远大于 堆地址。所以有可能在栈区,验证一下。

为了方便查看反汇编代码,我们把其他的代码都注释:

#include<iostream>
#include<unistd.h>
using namespace std;
int s2=0;
class cal
{
  public:
       void s(){};
       int s1;

};
int s3;
int main()
{
//  void *t,*t1;
//  t1=sbrk(0);
//  cout<<t1<<endl;
  cal c;
//  t=sbrk(0);
//  cout<<&s2<<endl;
//  cout<<&s3<<endl;
  cout<<&c.s1;
//  cout<<t<<endl;
}

反汇编:

这里写图片描述

发现:
lea 0x1c(%esp),%eax
mov %eax , 0x4(%esp)

这2条指令的作用是加载 c.s1的地址,以便cout函数进行输出。

我们发现一个有趣的现象,执行多次程序,返现输出结果不一样

这里写图片描述

这是因为linux引入了栈随机化的保护措施,所以这就是为何我们直接查看反汇编来验证。

所以通过上面的过程,发现我们的猜想是对的。。


版权声明:本文为tangyuanzong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/tangyuanzong/article/details/77131842