gpt4 book ai didi

c - 在c中释放和重置堆栈

转载 作者:行者123 更新时间:2023-11-30 16:39:19 25 4
gpt4 key购买 nike

所以我的程序中存在内存泄漏问题。我的函数 free_stack 之一是假设释放堆栈中的所有内存,并且在此函数调用之后不应使用堆栈。我的另一个问题是在我的 Reset_stack 函数中,该函数应该释放不再使用的任何内存。堆栈可以在函数调用后使用,并且该函数还应该将堆栈重置为其在 *make_stack 中的原始内容。我的程序没有这样做。这是我的代码。

struct int_stack *make_stack(int node_capacity){
struct int_stack *stk = malloc(sizeof(struct int_stack));
struct is_node *head = malloc(sizeof(struct is_node));

head->contents = malloc(node_capacity * sizeof(int));
head->next_index = 0;
head->next = NULL;
stk->node_capacity = node_capacity;
stk->head = head;
stk->size = 0;

return stk;
}


void free_stack(struct int_stack *stk) {
while(stk->head->next != NULL) {
free(stk);
}

}
void reset_stack(struct int_stack *stk) {
free_stack(stk);
*make_stack(stk->node_capacity);

}

最佳答案

调用 free 不会对您分配的内存以及您调用 free 的指针的值执行任何操作。而且您的函数 *make_stack(stk->node_capacity); 返回指向新分配的堆栈的指针,使用它。 stk = *make_stack(stk->node_capacity);

关于c - 在c中释放和重置堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47087615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com