C - How can I free dynamically allocated memory?

爷,独闯天下 提交于 2020-01-15 08:32:06

问题


Have a look at this piece of codes, it's part of a linked list.

int main()

{
    List* head1 = NULL;

    insertFront(&head1, 1);
    insertFront(&head1, 2);

    print(head1);

    free(head1);

    return 0;
}

another function is:

void insertFront(List** head, int value)

{
    List* node = (List*)malloc(sizeof(List));
    node->data = value;
    node->next = NULL;

    node->next = *head;
    *head = node;

   //free(node); essentially I am not freeing node
}

My questions are:

  1. Is my code going to cause memory leak problem?

  2. Should I need to free the allocated memory (dynamically) for node (Which is inside a function)?

  3. If I free head1, will the memory allocated for node also be freed? If yes, then how?


回答1:


You have a memory leak because you are only freeing the first node in the list. You don't want to free in the insertNode function otherwise you're immediately throwing away memory you just allocated.

At the end of your program, you need to traverse the list and free each element.

while (head1) {
    List *temp = head1;
    head1 = head1->next;
    free(temp);
}


来源:https://stackoverflow.com/questions/41900527/c-how-can-i-free-dynamically-allocated-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!