Thursday 15 March 2012

c - When to free node in linked list -


When I am inputting data in curr-> data , I first assign the memory crru = (noed *) molk (size of node); . Then I'm making the list and eventually finally print it, in a program, I have to free the memory that I have used, but I do not know when to do it. After the list is created, or after printing the list? Or can I do this?

  printf ("How many elements do you want to create?"); Scanf ("% d", and NumElem); Head = null; For (i = 0; i   

Can I insert data inside the current node?

Assume that you are reserving a local living room where you are planning a meeting And then when a party will release your reservation ... immediately after the reservation, after the meeting, but before the party, or after both the meeting and the party? > malloc and open are similar ... malloc reserves an area of ​​memory for your use and Free Reservations Reservation If you continue to use memory after canceling the reservation, then the behavior is undefined.

In your case, you need to free your entire list of nodes. You can do this in a loop, but there is a common trap: release a node before reaching your next indicator. The danger is that it almost always works in practice, but it is undefined and sometimes it will not work ... possibly some software control life-important machinery to learn best to control it right now To:

  zero free_list (NODE * list) {while (list) {NODE * next = list-> next; Free (list); List = next; }}   

Or in a slightly more compact form,

  zero free_list (NODE * list) {for (NODE * next; list; list = next) {Next = list-> next; Free (list); }}   

If your node has pointers for strings or other objects, which were malloc and they need to be free, free calls to Free_list will be done before auto-node free.

No comments:

Post a Comment