c – 为什么动态创建的对象与对象的大小相差两倍?

我编写了代码来创建动态创建对象的链接列表:

#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
the aligned_alloc,calloc,malloc,and realloc 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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...