最小化总的结构内存 [英] Minimize total struct memory
问题描述
我有一个struct
:
struct st
{
short a;
int *b;
char ch;
};
short
是2个字节
int*
在x64中为8个字节
char
是1个字节
short
is 2 bytes
int*
is 8 bytes in x64
char
is 1 bytes
以上所有内容都应该给我11个字节.但是如果执行sizeof(st)
,我将获得24个字节.为什么struct
使用更多的内存以及如何将内存减少到11个字节?
All the above together should give me 11 bytes. But if I do sizeof(st)
I get 24 bytes. Why the struct
uses more memory and how to reduce the memory to 11 bytes?
推荐答案
pragma pack
通常是使用的,但是它不如您希望的那样可移植.这是上面的文档:
pragma pack
is usually what is used, but its not as portable as you'd like. Here's the docs on it:
- Microsoft's pack
- GCC's Structure-Packing Pragmas
均提供#pragma pack(n)
,push
和pop
.
在没有包装的情况下,请尝试重新排序struct
:
In the absence of the packing, try reordering the struct
:
struct st
{
int *b;
short a;
char ch;
};
如果打包,访问数据时必须格外小心.您可能必须memmov
(或memcpy
),以确保在所有平台上的可移植性.如果不这样做,则可能会在Windows上遇到EXCEPTION_DATATYPE_MISALIGNMENT
或在Linux上遇到SIGBUS
错误.
You have to be careful about accessing data if its packed. You will probably have to memmov
(or memcpy
) it out to ensure portability across all platforms. If you don't, then you could encounter a EXCEPTION_DATATYPE_MISALIGNMENT
on Windows or a SIGBUS
error on Linux.
Microsoft在 IPF,x86和x64上的Windows数据对齐.
Microsoft has a good writeup on it at Windows Data Alignment on IPF, x86, and x64.
-Wstrict-aliasing
和-Wcast-align
将帮助您找到痛处.
-Wstrict-aliasing
and -Wcast-align
will help you find the sore spots.
这篇关于最小化总的结构内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!