微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐