我编写了代码来创建动态创建对象的链接列表:
#include <iostream> using namespace std; struct X { int i; X* x; }; void birth(X* head,int quant){ X* x = head; for(int i=0;i<quant-1;i++){ x->i = i+1; x->x = new X; x = x->x; } x->i = quant; x->x = 0; } void kill(X* x){ X* next; while(1==1){ cout << x->i << endl; cout << (long)x << endl; next = x->x; delete x; if(next == 0){ break; } else { x = next; } } } int main(){ cout << (long)sizeof(X) << endl; X* x = new X; birth(x,10); kill(x); return 0; }
这似乎是有效的,除了当你查看每个对象的地址时……
16 1 38768656 2 38768688 3 38768720 4 38768752 5 38768784 6 38768816 7 38768848 8 38768880 9 38768912 10 38768944
尽管X的大小仅为16位,但它们似乎相隔32位.我是如何创建对象的,或者这只是动态分配如何工作的结果?
解决方法
原因在7.22.3
C Standard的内存管理功能中说明:
The order and contiguity of storage allocated by successive calls to
thealigned_alloc
,calloc
,malloc
,andrealloc
functions is
unspecified. The pointer returned if the allocation succeeds is
suitably aligned so that it may be assigned to a pointer to any type
of object with a fundamental alignment requirement and then used to
access such an object or an array of such objects in the space
allocated
由于内存必须“适当对齐,以便可以将其分配给指向具有基本对齐要求的任何类型对象的指针”,因此malloc等人返回的内存倾向于从不同的,与平台相关的倍数开始 – 通常为8-或16字节边界.
并且因为new通常用malloc实现,所以这也适用于C new.