free()的正确使用

标签 c pointers

我开始提高我的基本 C 知识。

为此,我尝试使用指针数据类型。

我创建了一个这样的列表:

typedef struct lsEle *listPointer;
typedef struct lsEle {int index; listPointer next; int value;} element;

使用全局变量

listPointer header;

在我的 remove(int index) 函数中,我现在想要从索引处的列表中删除该元素。

void removeAtIndex(int index) {
    if (index < 0) {
        printf("You have to enter a index >= 0\n");
        return;
    } else {
        listPointer tmp = header;
        if (index == 0) {
            if (header->next == NULL) {
                header = NULL;
            } else {
                header = header->next;
            }
            free(tmp);
        } else {
            int counter = 0;
            while (1) {
                if (tmp->index == index - 1) {
                    break;
                }
                if (tmp->next != NULL) {
                    tmp = tmp->next;
                    counter++;
                } else {
                    break;
                }
            }
            if (index - 1 != counter) {
                printf("You have to enter a index <= %d\n", counter);
                return;
            } else {
                listPointer tmp_tmp = tmp->next;
                tmp->next = tmp_tmp->next;
                free(tmp_tmp);
            }
        }
        //Now update all index
        while (1) {
            if (tmp->next != NULL) {
                tmp = tmp->next;
                tmp->index = tmp->index - 1;
            } else {
                break;
            }
        }
    }
}

代码运行良好。

我现在的问题是:我正确使用 free() 吗?我的目标是从堆中删除元素“对象”。

如果我不使用免费服务会发生什么?函数从 remove 退出后,我无法再访问 tmp_tmp,但“已删除”对象是否仍保留在内存中?

最佳答案

Do I use free() correctly?

如果您之前使用 malloccallocrealloc 分配内存,则可以正确使用 free

What happens when I do not use free?

内存未释放,出现内存泄漏。

After the function exit from remove I don't have access to tmp_tmp any more, but does the "removed" object stay in memory?

您使用 free(tmp_tmp) 释放 tmp_tmp 指向的内存,以便从内存中删除对象。

关于free()的正确使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40698137/

相关文章:

c++ - 我的指针违反了访问限制错误,我想解释一下我应该在 Book 非默认构造函数中做什么

c - 在 C 中创建字符串并将其传递给函数的最佳方法?

c - 二叉搜索树节点删除错误

c - 具有结构指针数组的嵌套结构

c++ - OpenCV 窗口卡住

Windows API 编程中的组合框

c - C 中的信号处理程序显示困惑

c - 编译器如何评估 C 中的条件

c - 在 Linux 上将 * 作为命令行参数传递时的奇怪行为

c++ - 将堆上的结构从 C++ 转换为 C