如何使用free删除链表

How to delete linked list using free

我有这些结构:

typedef struct tStimulus_tc
{
    short                Key;
    struct tStimulus_tc *Next;

}Stimulus_tc;

struct Frame_tc
{
    int                   ID;     // Frame ID (0..MAX)
    int                   Count;  // Felt Count
    short                 sSize;  // Stimulus List Size
    Stimulus_tc          *sList;  // Stimulus List

};

如果我想释放一个 "struct Frame_tc" 这够了吗?

void freeFrame (Frame_tc *fTemp)
{
    free(fTemp);
}

或者我需要 运行 通过它的刺激并 1 乘 1 免费? 释放变量的正确方法是什么?

free() 获取先前分配的块并将其释放以供重用。它不知道也不关心缓冲区的内容。

虽然您可以编写递归释放指针的编译器,但这不是一个好主意:

static Stimulus_tc stim;
Frame_tc *fTemp = malloc(sizeof *fTemp);
fTemp->sList = &stim;
fTemp->sSize = 1;
free(fTemp); // if this recursively freed pointers, we would free a static object

只有你知道你的结构是如何构建的,因此你应该是破坏它的人。在您的情况下,这意味着遍历链表并释放每个成员。

在 C++ 中,建议使用更高级别的机制,例如使用 std::vector<Stimulus_tc> or std::list<Stimulus_tc>

在无法避免使用指针的情况下(您的情况并非如此),请考虑使用 smart pointers. And if you absolutely must manage memory the old way, use type-safe new[]/delete[]

在 C 中,如果 struct Frame_tc 包装器中的 Stimulus_tc 列表不是传统的 head/tail 列表(例如最后的 ->Next = NULL),而是数字list->sSize 中包含的节点数,您可以执行类似以下操作:

/* free all nodes in struct Frame_tc->Stimulus_tc list */
void free_list (struct Frame_tc *list)
{

    Stimulus_tc *iter = list->sList;    /* pointer to iterate list   */
    Stimulus_tc *victim = NULL;         /* pointer to node to delete */
    int n = list->sSize;                /* number of nodes to delete */

    if (iter ==  NULL) {
        fprintf (stderr,"print_list() warning: empty list.\n");
        return;
    }

    while (n--) {       /* free n nodes */
        victim = iter;
        iter = iter->Next;
        free (victim);
    }
}

如果将最终的 Next 指针设置为 NULL,则可以消除 int n = list->sSize; 并使用 while (iter) { ...

简单地遍历列表

如果在分配的每个节点中有额外的指针元素,您只需 free free (victim);

之前的那些值

仔细阅读,如果您有任何问题,请告诉我。