繁体   English   中英

释放并重置C中的堆栈

[英]Free and reset stack in c

所以我的程序内存泄漏有问题。 我的函数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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM