私はあなたがあなたが必要とする様々なメモリ操作を処理するための関数のセットを作成HashMapCollectionタイプのようなものを検討し提案します。
したがって、次のようなコードがある可能性があります。私はこれをテストしていないし、コンパイルしたこともありませんが、それは開始場所です。
下記のFreeHashMapCollection()
機能は、HashMapCollection
を処理して、管理データ構造を解放する前に、その内容を解放します。これはあなたがしたいことではないかもしれないので、それはあなたが考慮すべきものです。
以下の考え方はHashMapCollection
構造体のための単一のポインタを持つことであり、HashMapNode
構造体の配列またはリストは管理データの直後にあるため、単一のfree()
がすべてを一度に解放します。
typedef struct _TAGHashMapNode {
void *key, *value;
struct _TAGHashMapNode *next;
} HashMapNode;
typedef struct {
int iCapacity; // max number of items
int iSize; // current number of items
HashMapNode *table; // pointer to the HashMapNode table
} HashMapCollection;
そして適切に初期化され、特定の容量のHashMapCollection
を割り当てる機能を有します。
HashMapCollection *AllocateHashMapCollection (int iCapacity)
{
HashMapCollection *p = malloc (sizeof(HashMapCollection) + iCapacity * sizeof(HashMapNode));
if (p) {
p->table = (HashMapNode *)(p + 1);
p->iCapacity = iCapacity;
p->iSize = 0;
memset (p->table, 0, sizeof(HashMapNode) * iCapacity);
}
return p;
}
HashMapCollection *ReallocHashMapCollection (HashMapCollection *p, int iNewCapacity)
{
HashMapCollection *pNew = realloc (p, sizeof(HashMapCollection) + sizeof(HashMapNode) * iNewCapacity);
if (pNew) {
pNew->table = (HashMapNode *)(pNew + 1);
if (p == NULL) {
// if p is not NULL then pNew will have a copy of that.
// if p is NULL then this is basically a malloc() so initialize pNew data.
pNew->iCapacity = pNew->iSize = 0;
}
if (iNewCapacity > pNew->iCapacity) {
// added more memory so need to zero out that memory.
memset (pNew->table + iCapacity, 0, sizeof(HashMapNode) * (iNewCapacity - pNew->iCapacity));
}
pNew->iCapacity = iNewCapacity; // set our new current capacity
p = pNew; // lets return our new memory allocated.
}
return p; // return either old pointer if realloc() failed or new pointer
}
void FreeHashMapCollection (HashMapCollection *p)
{
// go through the list of HashMapNode items and free up each pair then
// free up the HashMapCollection itself.
for (iIndex = 0; iIndex < p->iCapacity; iIndex++) {
if (p->table[iIndex].key) free (p->table[iIndex].key);
if (p->table[iIndex].value) free (p->table[iIndex].value);
// WARNING ***
// if these next pointers are actually pointers inside the array of HashMapNode items
// then you would not do this free as it is unnecessary.
// this free is only necessary if next points to some memory area
// other than the HashMapNode table of HashMapCollection.
if (p->table[iIndex].next) free (p->table[iIndex].next);
// even though we are going to free this, init to NULL
p->table[iIndex].key = NULL;
p->table[iIndex].value = NULL;
p->table[iIndex].next = NULL;
}
free (p); // free up the memory of the HashMapCollection
}
'malloc'で割り当てられたメモリはゼロで初期化されません。これを行うには、['memset'](http://man7.org/linux/man-pages/man3/memset.3.html)を使うことができます。 'struct Node ** table;'はポインタの "リスト"を作るが、あなたは 'Node'sの"リスト "を割り当てた。 – Tim