是否有可能在C中一般地释放链表的内存

arm*_*inb 2 c malloc free struct linked-list

如果我在C中有几个链接结构,如:

struct structA {
    int a;
    int b;
    struct structA *next;
}

struct structB {
    char a;
    int b;
    struct structB *next;
}
Run Code Online (Sandbox Code Playgroud)

我动态分配内存,如下所示:

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));
Run Code Online (Sandbox Code Playgroud)

我总是必须为每个结构类型释放它,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)

还是有通用的解决方案吗?我假设没有其他解决方案,因为该free()过程必须知道必须释放多少字节.但也许我错了,有人可以教我更好.

wil*_*ser 5

标准方法是使"list part"成为结构的第一个元素,并让每个派生的 struct共享同一个前缀.由于保证第一个元素位于零偏移处,因此这将起作用.示例代码段:

#include <stdlib.h>
#include <string.h>

struct list {
    struct list *next;
    };
struct structA {
    struct list list;
    int a;
    int b;
    };

struct structB {
    struct list list;
    char a;
    int b;
    };

void *create_any(size_t size) 
{
    struct list *this;
    this = malloc (size);
    if (!this) return this;
    memset(this, 0, size);
    this->next = NULL;
    return this;
}


void free_all_any(struct list **lp) {
    struct list *tmp;
    while ((tmp = *lp)) { *lp = tmp->next; free(tmp); }
}
#define CREATE_A() create_any(sizeof(struct structA))
#define CREATE_B() create_any(sizeof(struct structB))
#define FREE_A(pp) free_any((struct list **) pp)
#define FREE_B(pp) free_any((struct list **) pp)

int main(void)
{
struct structA *ap;
struct structB *bp;

ap = CREATE_A ();
bp = CREATE_B ();

// some code here ...

FREE_A( &ap);
FREE_B( &bp);

return 0;
}
Run Code Online (Sandbox Code Playgroud)

这或多或少是linux内核中使用的方法,但在那里使用了更多的预处理器魔法.(显然没有malloc)