马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 kangels 于 2013-3-19 10:23 编辑
0 @$ v& D2 L7 y1 \# }6 y: _( m( S( i9 A. s
丢失的类型信息
" A$ \; J- D4 R, F猜测+ k0 \+ x# p' c+ g6 a E/ Y
指针变量应该存储两方面的信息:地址,类型信息
* z8 t+ p) a* M8 u7 b j0 ~9 X) o8 M- O9 A' S* e+ c. C
实证; N6 D% g/ [- ~' ~1 \( _( a5 q$ O
用sizeof(),float *,int*,double *....都是4字节没有存储类型信息只有地址信息
2 H5 @2 u9 _1 f. I& ^反汇编一段代码来看看
) G3 l& Y( f; h, o, o/ y实例1:- s8 T/ q! y5 m8 K3 j! ]$ c# T
#include <stdio.h> int gi; int * pi; void main(int argc, char **argv) { pi = &gi; *pi = 12; } 1: #include <stdio.h> 2: int gi; 3: int * pi; 4: void main(int argc, char **argv) 5: { 00411370 push ebp 00411371 mov ebp,esp 00411373 sub esp,0C0h 00411379 push ebx 0041137A push esi 0041137B push edi 0041137C lea edi,[ebp+FFFFFF40h] 00411382 mov ecx,30h 00411387 mov eax,0CCCCCCCCh 0041138C rep stos dword ptr es:[edi] 6: pi = &gi; 0041138E mov dword ptr ds:[00417140h],417144h 7: *pi = 12; 00411398 mov eax,dword ptr ds:[00417140h] 0041139D mov dword ptr [eax],0Ch 8: } 004113A3 xor eax,eax 004113A5 pop edi 004113A6 pop esi 004113A7 pop ebx 004113A8 mov esp,ebp 004113AA pop ebp 004113AB ret
! C! _0 U$ h7 `! p
6 i( \* ` J2 D# V实例2:4 u) E4 e* ^: d, i4 _
#include <stdio.h> short gs; short * ps; void main(int argc, char **argv) { ps = &gs; *ps = 12; } 5 e5 ~) `0 b( @% T* _, E6 a
1: #include <stdio.h> 2: short gs; 3: short * ps; 4: void main(int argc, char **argv) 5: { 00411370 push ebp 00411371 mov ebp,esp 00411373 sub esp,0C0h 00411379 push ebx 0041137A push esi 0041137B push edi 0041137C lea edi,[ebp+FFFFFF40h] 00411382 mov ecx,30h 00411387 mov eax,0CCCCCCCCh 0041138C rep stos dword ptr es:[edi] 6: ps = &gs; 0041138E mov dword ptr ds:[00417140h],417144h 7: *ps = 12; 00411398 mov eax,0Ch 0041139D mov ecx,dword ptr ds:[00417140h] 004113A3 mov word ptr [ecx],ax 8: } 004113A6 xor eax,eax 004113A8 pop edi 004113A9 pop esi 004113AA pop ebx 004113AB mov esp,ebp 004113AD pop ebp 004113AE ret
2 S, e% \$ I1 D# N2 ^" p# {1 j7 u3 Y# O) |; c) R1 b8 W
实例3:
( _( h5 O& E: @4 d+ T% m#include <stdio.h> char gc; char * pc; void main(int argc, char **argv) { pc = &gc; *pc = 12; } 6 a0 C: Z) \3 y8 o$ P
1: #include <stdio.h> 2: char gc; 3: char * pc; 4: void main(int argc, char **argv) 5: { 00411370 push ebp 00411371 mov ebp,esp 00411373 sub esp,0C0h 00411379 push ebx 0041137A push esi 0041137B push edi 0041137C lea edi,[ebp+FFFFFF40h] 00411382 mov ecx,30h 00411387 mov eax,0CCCCCCCCh 0041138C rep stos dword ptr es:[edi] 6: pc = &gc; 0041138E mov dword ptr ds:[00417140h],417144h 7: *pc = 12; 00411398 mov eax,dword ptr ds:[00417140h] 0041139D mov byte ptr [eax],0Ch 8: } 004113A0 xor eax,eax 004113A2 pop edi 004113A3 pop esi 004113A4 pop ebx 004113A5 mov esp,ebp 004113A7 pop ebp 004113A8 ret
; `4 n9 E' S; C& C( c% H, H, I! }7 D) o/ r( \7 f; l5 v( d
可以看出指针的类型信息决定了赋值/读取时读/写多少个字节。
" N$ ^& g: [+ J: e/ k& O读/写多少字节的信息不是存放在指针变量中,而是放到了与该地址相关的赋值指令中。
5 b/ f% R0 H- L7 ] |