简体   繁体   中英

Free and reset stack in c

So I'm having a problem with memory leaks in my program. One of my functions free_stack is suppose free all the memory in the stack and the stack should not be used after this function call. My other problem is in my reset_stack function which is suppose to free any memory not in use anymore. The stack can be used after the function call and the function is also suppose to reset the stack to its original contents in *make_stack.My program is not doing this. Here's my code.

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);

}

calling free doesn't do anything to your allocated memory, and also value of pointers you called free on. And also your function *make_stack(stk->node_capacity); returns pointer to the newly allocated stack, use that. stk = *make_stack(stk->node_capacity); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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