gcc使用malloc进行内存对齐 [英] gcc memory alignment using malloc
问题描述
我有以下结构:
#定义M 3
#pragma pack(push)
#pragma pack(1)
struct my_btree_node {
struct my_btree_node * pointers [M];
unsigned char * keys [M - 1];
int data [M - 1];
unsigned char number_of_keys;
};
#pragma pack(pop)
sizeof(struct my_btree_node )函数为这个结构返回一个49字节的值。是否使用 malloc
为该结构分配内存会返回一个64字节的数据块,因为在64位系统中指针是16字节对齐的,还是确实是49字节?
是否有一种方法可以将内存与小于2的幂比对,并且可以在应用程序内获得分配内存的真实大小?
我想减少填充字节的数量以节省内存。我的应用程序分配了数百万个结构,我不想浪费内存。
code>使用内部堆结构。它依赖于实现,但人们可能会期望内存由全部(内部)块分配。所以通常不可能通过一个 malloc
调用分配恰好49个字节。你可以在 malloc
之上建立一个你自己的子系统来做到这一点,但我没有理由为什么你可能需要它。 PS为了减少内存浪费,你可以预先分配一个由100个结构组成的数组,当你只需要一个时,就返回& a [i],直到所有的空闲索引被浪费。由于数组永远不会被填充,所以内存浪费将会减少大约100倍。
I've the following struct:
#define M 3
#pragma pack(push)
#pragma pack(1)
struct my_btree_node {
struct my_btree_node *pointers[M];
unsigned char *keys[M - 1];
int data[M - 1];
unsigned char number_of_keys;
};
#pragma pack(pop)
The sizeof(struct my_btree_node)
function returns a value of 49 byte for this struct. Does allocating memory for this struct using malloc
return a 64 byte block because on 64 bit systems pointers are 16-byte-aligned or will it indeed be 49 bytes?
Is there a way to align memory with a smaller power of two than 16 and is it possible to get the true size of the allocated memory inside the application?
I want to reduce the number of padding bytes in order to save memory. My applications allocates millions of those structs and I do not want to waste memory.
malloc
uses internal heap-structure. It is implementation-dependent yet one may expect that the memory is allocated by a whole number of (internal) blocks. So usually it's not possible to allocate exactly 49 bytes by a single malloc
call. You can build some subsystem of your own on top of malloc
to do this, yet I see no reason why you may want it.
P.S. To reduce memory wasting, you can pre-allocate an array consisting of, say, 100 structs, when you need just one more, and return &a[i] until all free indexes are wasted. As arrays are never padded, the memory wasting would be reduced in about 100 times.
这篇关于gcc使用malloc进行内存对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!