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

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

概述我编写了代码来创建动态创建对象的链接列表: #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 = 我编写了代码来创建动态创建对象的链接列表:

#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;}

这似乎是有效的,除了当你查看每个对象的地址时……

161387686562387686883387687204387687525387687846387688167387688488387688809387689121038768944

尽管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 – 为什么动态创建的对象与对象的大小相差两倍?全部内容,希望文章能够帮你解决c – 为什么动态创建的对象与对象的大小相差两倍?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1221416.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存