为了避免内存泄漏,我们需要小心处理重新分配(稍后会详细介绍)。重新分配函数:
void *realloc(void *ptr, size_t size)
, 在哪里
ptr
=指向原始(malloc
'ed)内存块的指针,和
size
= 内存块的新大小(以字节为单位)。
realloc
返回动态分配的内存块的新位置(可能已更改) -如果重新分配失败,则返回 NULL!如果它返回 NULL,则原始内存保持不变,因此您必须始终使用临时变量作为 的返回值realloc
。
一个示例将对此进行澄清(兴趣点:realloc 语法类似于 malloc 的(不需要额外的强制转换等),并且在 realloc 之后,您需要为新对象生成与 malloc 之后相同的步骤):
struct st_temp **temp_struct;
temp_struct = malloc(20 * sizeof *temp_struct);
if (temp_struct == NULL) { /* handle failed malloc */ }
for (int i = 0; i < 20; ++i) {
temp_struct[i] = malloc(sizeof *temp_struct[i]);
temp_struct[i]->prod = "foo";
}
// We need more space ... remember to use a temporary variable
struct st_temp **tmp;
tmp = realloc(temp_struct, 30 * sizeof *temp_struct);
if (tmp == NULL) {
// handle failed realloc, temp_struct is unchanged
} else {
// everything went ok, update the original pointer (temp_struct)
temp_struct = tmp;
}
for (int i = 20; i < 30; ++i) { // notice the indexing, [20..30)
// NOTICE: the realloc allocated more space for pointers
// we still need to allocate space for each new object
temp_struct[i] = malloc(sizeof *temp_struct[i]);
temp_struct[i]->prod = "bar";
}
// temp_struct now "holds" 30 temp_struct objects
// ...
// and always do remember, in the end
for (int i = 0; i < 30; ++i)
free(temp_struct[i]);
free(temp_struct);
请注意,这实际上不是一个结构数组,而是一个指向结构的指针数组 - 如果您愿意,甚至可以是一个结构数组的数组。在最后一种情况下,每个子数组的长度为 1(因为我们只为一个结构分配空间)。