这是一个例子:
#include <stdlib.h>
typedef struct auxiliarRegistre { ... } clients;
int arrSize = SOME_START_SIZE;
clients *arr = malloc( arrSize * sizeof *arr );
/**
* Do stuff with arr. When you need to extend the buffer, do the following:
*/
clients *tmp = realloc( clients, sizeof *arr * ( arrSize * 2));
if ( tmp )
{
arr = tmp;
arrSize *= 2;
}
每次需要扩展缓冲区时都将缓冲区的大小加倍是一种常见的策略;这往往会最大限度地减少对realloc
. 它还可能导致严重的内部碎片化;如果你有 128 个元素,而你只需要再存储一个,你最终会分配 256 个元素。您也可以按固定金额延期,例如
clients *tmp = realloc( clients, sizeof *arr * ( arrSize + extent ));
if ( tmp )
{
arr = tmp;
arrSize += extent;
}
请注意,您不想将结果realloc
直接分配给缓冲区;如果由于错误而返回 NULL,您将丢失对已分配内存的引用,从而导致内存泄漏。此外,在您知道调用成功之前,您不希望更新数组大小。