C にいくつかのリンクされた構造がある場合:
struct structA {
int a;
int b;
struct structA *next;
}
struct structB {
char a;
int b;
struct structB *next;
}
そして、次のようにメモリを動的に割り当てます。
struct structA *mystructA = (struct structA*) malloc(sizeof(struct structA));
mystructA->next = (struct structA*) malloc(sizeof(struct structA));
struct structB *mystructB = (struct structB*) malloc(sizeof(struct structB));
mystructB->next = (struct structB*) malloc(sizeof(struct structB));
次のように、構造体の種類ごとに常に解放する必要がありますか?
struct structA *p, *pNext;
for (p = mystructA; p != NULL; p = pNext) {
pNext = p->next;
free(p);
}
struct structB *p, *pNext;
for (p = mystructB; p != NULL; p = pNext) {
pNext = p->next;
free(p);
}
または一般的な解決策はありますか?free()
プロシージャは解放する必要があるバイト数を知る必要があるため、他に解決策はないと思います。しかし、多分私は間違っていて、誰かが私にもっとよく教えてくれるでしょう。