Minimize total struct memory

≯℡__Kan透↙ 提交于 2019-12-11 02:56:40

问题


I have a struct:

struct st
{
    short a;
    int *b;
    char ch;
};

short is 2 bytes
int* is 8 bytes in x64
char is 1 bytes

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?


回答1:


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

Both provide #pragma pack(n), push, and pop.

In the absence of the packing, try reordering the struct:

struct st
{
    int *b;
    short a;
    char ch;
};

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 has a good writeup on it at Windows Data Alignment on IPF, x86, and x64.

-Wstrict-aliasing and -Wcast-align will help you find the sore spots.




回答2:


I know this is late and I know you already accepted an answer but this can also work.. You'll get 12 bytes.. NOT 11. I'm not sure if it's portable but I think it is. See here: http://en.cppreference.com/w/cpp/language/alignas

#include <iostream>

struct alignas(char) aligned_struct
{
    short a;
    int *b;
    char ch;
};


int main()
{
    std::cout<<sizeof(aligned_struct);
}

EDIT:

VS2012 does NOT include alignas in their compiler according to: http://msdn.microsoft.com/en-us/library/vstudio/hh567368(v=vs.110).aspx

It doesn't seem to need the above in VS2012 though. For some reason, with or without the above, it still prints 12:

struct aligned_struct
{
    short a;
    int* b;
    char ch;
};


int _tmain(int argc, _TCHAR* argv[])
{
    std::cout<<sizeof(aligned_struct); //prints 12
    std::cin.get();
    return 0;
}


来源:https://stackoverflow.com/questions/21010346/minimize-total-struct-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!