实例代码(栈地址增长方向、vtable对类size的影响、对象最小size概念、结构体对齐规则(对齐参数)、sizeof(指针),free与delete的区别)
测试代码:
1、栈上局部变量地址增长方向测试(输出中局部变量地址是否连续性,与编译器有关)。
2、vtable在类中size的作用,对象最小size概念(one bite)。
3、关于结构体对齐的问题。(可以设置结构体是否对齐,除了__attribute还有#param参数;结构体对齐的原则,从编译器默认对齐的字节数与结构体各成员中最大对齐字节数两者中,选择较小的一个。
4、一段代码中的连续分配的堆上内存,地址不一定是连续的,可能无规律。
5、sizeof(pType)得到是指针的大小(机器字)
1 #include <stdio.h> 2 #include <string> 3 class A 4 { 5 public: 6 A() 7 { 8 printf("A() this:%p\n", this); 9 } 10 virtual ~A() 11 { 12 printf("~A() this:%p\n", this); 13 } 14 private: 15 char testbit; 16 }; 17 18 struct B 19 { 20 public: 21 B(){}; 22 ~B(){}; 23 }; 24 25 struct C 26 { 27 char testbit; 28 int testInt; 29 double testdouble; 30 }; 31 32 struct D 33 { 34 char testbit; 35 int testint; 36 double testdouble; 37 }__attribute((packed)); 38 39 int main () 40 { 41 { 42 char src[]="123456789"; 43 char dst[]="1234"; 44 printf("dst--%p src--%p\n",dst,src); 45 strcpy(dst, src); 46 printf("dst--%s src--%s\n",dst,src); 47 } 48 { 49 char *pfirst = new char[7]; 50 char *psecond = new char[6]; 51 printf("pfirst:%p psecond:%p, sizeof(pfirst):%d\n", pfirst, psecond, sizeof(pfirst)); 52 delete pfirst; 53 delete psecond; 54 } 55 { 56 A *pA = new A; 57 B *pB = new B; 58 C *pC = new C; 59 D *pD = new D; 60 printf("pA:%p sizeA:%d sizeof(pA):%d pB:%p sizeB:%d\n",pA, sizeof(A), sizeof(pA), pB, sizeof(B)); 61 printf("pC:%p sizeC:%d ,sizeof(pc):%d pD:%p, sizeD:%d\n", pC, sizeof(C), sizeof(pC), pD, sizeof(D)); 62 delete pA,pA = 0; 63 delete pB,pB = 0; 64 delete pC,pC = 0; 65 delete pD,pD = 0; 66 pB = new B[10]; 67 pA = new A; 68 A *pAs = new A[2]; 69 printf("pA:%p sizeA:%d sizeof(pA):%d pB:%p sizeB:%d\n",pA, sizeof(A), sizeof(pA), pB, sizeof(B)); 70 printf("pAs:%p ,sizeof(pAs):%d \n", pAs, sizeof(pAs)); 71 delete[] pB,pB = 0; 72 free(pA);//horror 73 delete[] pAs; 74 75 } 76 return 0; 77 }
打印输出:
dst--0xbf8a0215 src--0xbf8a021a
dst--123456789 src--6789
pfirst:0x9813008 psecond:0x9813018, sizeof(pfirst):4
A() this:0x9813018
pA:0x9813018 sizeA:8 sizeof(pA):4 pB:0x9813008 sizeB:1
pC:0x9813028 sizeC:16 ,sizeof(pc):4 pD:0x9813040, sizeD:13
~A() this:0x9813018
A() this:0x9813008
A() this:0x981302c
A() this:0x9813034
pA:0x9813008 sizeA:8 sizeof(pA):4 pB:0x9813044 sizeB:1
pAs:0x981302c ,sizeof(pAs):4
~A() this:0x9813034
~A() this:0x981302c
posted on 2012-12-23 00:04 hj_daydayup 阅读(209) 评论(0) 收藏 举报
浙公网安备 33010602011771号