为什么char实际上占用内存中的4个字节

为什么char实际上占用内存中的4个字节

本文介绍了C问题:为什么char实际上占用内存中的4个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小程序,以检查在我的内存中占用多少字节,并且它显示char实际上占用内存中的4个字节。我理解这主要是因为字对齐,并没有看到char只有1个字节的优势。为什么不使用4字节的char?

  int main(void)
{
int a;
char b;
int c;
a = 0;
b ='b';
c = 1;
printf(%p\\\
,& a);
printf(%p\\\
,& b);
printf(%p\\\
,& c);
return 0;
}

输出:
0x7fff91a15c58
0x7fff91a15c5f
0x7fff91a15c54



更新:
我不相信malloc只会为char分配1个字节,即使sizeof(char)作为参数传递,因为malloc包含一个标题将确保标题是字对齐的。任何意见?



Update2:
如果被要求有效地使用内存而不填充,唯一的办法是创建一个特殊的内存分配器?或者是否可以禁用填充?

解决方案

你有int,char,int



请参见为什么限制字节对齐?

 字节0字节1字节2字节3 
0x1000
0x1004 X0 X1 X2 X3
0x1008
0x100C Y0 Y1 Y2

如果将它们存储在4字节,字节和4字节的形式,它将采取2个cpu周期来检索 int c 和一些位移,以获得c的实际值正​​确对齐,用作int 。


I wrote a small program to check how many bytes char occupies in my memory and it shows char actually occupies 4 bytes in memory. I understand it's mostly because of word alignment and don't see advantage of a char being only 1 byte. Why not use 4 bytes for char?

int main(void)
{
  int a;
  char b;
  int c;
  a = 0;
  b = 'b';
  c = 1;
  printf("%p\n",&a);
  printf("%p\n",&b);
  printf("%p\n",&c);
  return 0;
}

Output: 0x7fff91a15c58 0x7fff91a15c5f 0x7fff91a15c54

Update:I don't believe that malloc will allocate only 1 byte for char, even though sizeof(char) is passed as argument because, malloc contains a header will makes sure that header is word aligned. Any comments?

Update2:If you are asked to effectively use memory without padding, is the only way is to create a special memory allocator? or is it possible to disable padding?

解决方案

You have int, char, int

See the image here under "Why Restrict Byte Alignment?"http://www.eventhelix.com/realtimemantra/ByteAlignmentAndOrdering.htm

          Byte 0 Byte 1 Byte 2  Byte 3
0x1000
0x1004  X0     X1     X2      X3
0x1008
0x100C         Y0     Y1      Y2

If it had stored them in 4-byte, 1-byte and 4-byte form, it would have taken 2 cpu cycles to retrieve int c and some bit-shifting to get the actual value of c aligned properly for use as an int.

这篇关于C问题:为什么char实际上占用内存中的4个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 16:16