获得适合 malloc 函数的大小
Getting the size right for the malloc function
我经常发现自己花了很多时间来弄清楚当我有一个不明显的类型时我应该如何正确调整 malloc
的大小。这是一个例子:
typedef struct {
char* key;
char* value;
} hash_item;
typedef struct {
int size; // max size of the table
int count; // how many items are currently in the table
hash_item** items; // will have size * hash_items in the array
} hash_table;
现在,当我创建一个新的哈希表时,我将执行如下操作:
hash_table *table = malloc(sizeof(hash_table));
table->items = malloc(sizeof(*hash_item) * size); // this is tricky for me
'sizing' 正确吗?我怎么知道 sizeof(*hash_item)
是正确的单位大小,而不是例如:
sizeof(hash_item)
sizeof(table->items[0])
sizeof(*(table->items))
当 malloc
引用非原始数据类型时,是否有一个很好的 tumb 规则来确定它的大小?
您通常不需要使用 malloc
大小的类型,您应该避免使用它。您可以改用“示例对象”:
PointerToThing = malloc(NumberOfThings * sizeof *PointerToThing);
所以这很简单:*PointerToThing
是指向的东西的类型,所以它的大小就是你想要的。
此外,它减少了某些错误的可能性:
- 如果您尝试为
PointerToThing
指向的内容键入类型描述,则可能会出错。 *PointerToThing
很简单,所以人们不太可能犯错,尤其是一旦它成为习惯。
- 如果您以后修改程序并更改
PointerToThing
的类型,您必须记住也要搜索使用该类型的所有地方并在那里进行更改。使用上面的方法,类型没有出现,所以不能忽略——类型改变时没有改变; sizeof
会自动适应 *PointerToThing
的任何类型。
而PointerToThing
不一定是简单变量。它可以是一个表达式,例如 table->items
,您可以使用 malloc(NumberOfItems * sizeof *table->items)
.
我经常发现自己花了很多时间来弄清楚当我有一个不明显的类型时我应该如何正确调整 malloc
的大小。这是一个例子:
typedef struct {
char* key;
char* value;
} hash_item;
typedef struct {
int size; // max size of the table
int count; // how many items are currently in the table
hash_item** items; // will have size * hash_items in the array
} hash_table;
现在,当我创建一个新的哈希表时,我将执行如下操作:
hash_table *table = malloc(sizeof(hash_table));
table->items = malloc(sizeof(*hash_item) * size); // this is tricky for me
'sizing' 正确吗?我怎么知道 sizeof(*hash_item)
是正确的单位大小,而不是例如:
sizeof(hash_item)
sizeof(table->items[0])
sizeof(*(table->items))
当 malloc
引用非原始数据类型时,是否有一个很好的 tumb 规则来确定它的大小?
您通常不需要使用 malloc
大小的类型,您应该避免使用它。您可以改用“示例对象”:
PointerToThing = malloc(NumberOfThings * sizeof *PointerToThing);
所以这很简单:*PointerToThing
是指向的东西的类型,所以它的大小就是你想要的。
此外,它减少了某些错误的可能性:
- 如果您尝试为
PointerToThing
指向的内容键入类型描述,则可能会出错。*PointerToThing
很简单,所以人们不太可能犯错,尤其是一旦它成为习惯。 - 如果您以后修改程序并更改
PointerToThing
的类型,您必须记住也要搜索使用该类型的所有地方并在那里进行更改。使用上面的方法,类型没有出现,所以不能忽略——类型改变时没有改变;sizeof
会自动适应*PointerToThing
的任何类型。
而PointerToThing
不一定是简单变量。它可以是一个表达式,例如 table->items
,您可以使用 malloc(NumberOfItems * sizeof *table->items)
.