我开始提高我的基本 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?
如果您之前使用 malloc
、calloc
或 realloc
分配内存,则可以正确使用 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/