加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:36:06 所属栏目:百科 来源:网络整理
导读:我编写了代码来创建动态创建对象的链接列表: #include iostreamusing namespace std;struct X { int i; X* x;};void birth(X* head,int quant){ X* x = head; for(int i=0;iquant-1;i++){ x-i = i+1; x-x = new X; x = x-x; } x-i = quant; x-x = 0;}void k
我编写了代码来创建动态创建对象的链接列表:

#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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读