首页 > 代码库 > 《coredump问题原理探究》Linux x86版6.1节C++风格数据结构内存布局之无成员变量的类

《coredump问题原理探究》Linux x86版6.1节C++风格数据结构内存布局之无成员变量的类

在探究完C风格数据结构内存布局之后,接着探究C++风格数据结构内存布局。

虽然最简单的类是没有任何成员变量和成员函数,但由于没什么意义,不值得探究。在这里,就先探究一下没有任何成员变量和虚函数,只有成员函数的类。

先看一下例子:

  1	 #include <stdio.h>
  2	 class xuzhina_dump_c06_s1
  3	 {
  4	     public:
  5	         void hello()
  6	         {
  7	             printf( "hello\n" );
  8	         }
  9	         void print()
 10	         {
 11	             printf( "this:%p\n", this);
 12	         }
 13	 };
 14 
 15	 int main()
 16	 {
 17	     xuzhina_dump_c06_s1 test;
 18	     printf( "address of test:%p\n", &test );
 19	     test.print();
 20	     test.hello();
 21	     return 0;
 22	 }

汇编代码:

(gdb) disassemble main

Dump of assembler code for function main:

  0x080485a0 <+0>:    push   %ebp

  0x080485a1 <+1>:    mov    %esp,%ebp

  0x080485a3 <+3>:    and    $0xfffffff0,%esp

  0x080485a6 <+6>:    sub    $0x20,%esp

  0x080485a9 <+9>:    lea    0x1f(%esp),%eax

  0x080485ad <+13>:   mov    %eax,0x4(%esp)

  0x080485b1 <+17>:   movl   $0x80486c3,(%esp)

  0x080485b8 <+24>:   call   0x8048460<printf@plt>

  0x080485bd <+29>:   lea    0x1f(%esp),%eax

  0x080485c1 <+33>:   mov    %eax,(%esp)

  0x080485c4 <+36>:   call   0x80485fa<_ZN19xuzhina_dump_c06_s15printEv>

  0x080485c9 <+41>:   lea    0x1f(%esp),%eax

  0x080485cd <+45>:   mov    %eax,(%esp)

  0x080485d0 <+48>:   call   0x80485e6<_ZN19xuzhina_dump_c06_s15helloEv>

   0x080485d5 <+53>:    mov   $0x0,%eax

  0x080485da <+58>:   jmp    0x80485e4 <main+68>

  0x080485dc <+60>:   mov    %eax,(%esp)

  0x080485df <+63>:   call   0x8048490<_Unwind_Resume@plt>

  0x080485e4 <+68>:   leave 

  0x080485e5 <+69>:   ret    

End of assembler dump.

其中这段指令

   0x080485a9 <+9>:     lea    0x1f(%esp),%eax
   0x080485ad <+13>:    mov    %eax,0x4(%esp)
   0x080485b1 <+17>:    movl   $0x80486c3,(%esp)
   0x080485b8 <+24>:    call   0x8048460 <printf@plt>

是对应

18	     printf( "address of test:%p\n", &test );

也就是说,esp+0x1f放着是this指针。

由这两段指令,

   0x080485bd <+29>:    lea    0x1f(%esp),%eax
   0x080485c1 <+33>:    mov    %eax,(%esp)
   0x080485c4 <+36>:    call   0x80485fa <_ZN19xuzhina_dump_c06_s15printEv>

   0x080485c9 <+41>:    lea    0x1f(%esp),%eax
   0x080485cd <+45>:    mov    %eax,(%esp)
   0x080485d0 <+48>:    call   0x80485e6 <_ZN19xuzhina_dump_c06_s15helloEv>

可知一个对象在调用成员函数之前,都会把this指针作为成员函数的第一个参数。也就是说,类的成员函数默认都有参数,其中第一个参数就是对象的this指针。


《coredump问题原理探究》Linux x86版6.1节C++风格数据结构内存布局之无成员变量的类