您的位置:首页 > 编程语言

实例代码(栈地址增长方向、vtable对类size的影响、对象最小size概念、结构体对齐规则(对齐参数)、sizeof(指针),free与delete的区别)

2012-12-23 00:04 816 查看
测试代码:

1、栈上局部变量地址增长方向测试(输出中局部变量地址是否连续性,与编译器有关)。

2、vtable在类中size的作用,对象最小size概念(one bite)。

3、关于结构体对齐的问题。(可以设置结构体是否对齐,除了__attribute还有#param参数;结构体对齐的原则,从编译器默认对齐的字节数与结构体各成员中最大对齐字节数两者中,选择较小的一个。

4、一段代码中的连续分配的堆上内存,地址不一定是连续的,可能无规律。

5、sizeof(pType)得到是指针的大小(机器字)

#include <stdio.h>
#include <string>
class A
{
public:
A()
{
printf("A() this:%p\n", this);
}
virtual ~A()
{
printf("~A() this:%p\n", this);
}
private:
char testbit;
};

struct B
{
public:
B(){};
~B(){};
};

struct C
{
char testbit;
int testInt;
double testdouble;
};

struct D
{
char testbit;
int testint;
double testdouble;
}__attribute((packed));

int main ()
{
{
char src[]="123456789";
char dst[]="1234";
printf("dst--%p src--%p\n",dst,src);
strcpy(dst, src);
printf("dst--%s src--%s\n",dst,src);
}
{
char *pfirst = new char[7];
char *psecond = new char[6];
printf("pfirst:%p   psecond:%p, sizeof(pfirst):%d\n", pfirst, psecond, sizeof(pfirst));
delete pfirst;
delete psecond;
}
{
A *pA = new A;
B *pB = new B;
C *pC = new C;
D *pD = new D;
printf("pA:%p sizeA:%d sizeof(pA):%d pB:%p sizeB:%d\n",pA, sizeof(A), sizeof(pA), pB, sizeof(B));
printf("pC:%p sizeC:%d ,sizeof(pc):%d pD:%p, sizeD:%d\n", pC, sizeof(C), sizeof(pC), pD, sizeof(D));
delete pA,pA = 0;
delete pB,pB = 0;
delete pC,pC = 0;
delete pD,pD = 0;
pB = new B[10];
pA = new A;
A *pAs = new A[2];
printf("pA:%p sizeA:%d sizeof(pA):%d pB:%p sizeB:%d\n",pA, sizeof(A), sizeof(pA), pB, sizeof(B));
printf("pAs:%p ,sizeof(pAs):%d \n", pAs, sizeof(pAs));
delete[] pB,pB = 0;
free(pA);//horror
delete[] pAs;

}
return 0;
}


打印输出:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐