free the memory of linked list.

This is a discussion on free the memory of linked list. within the C Programming forums, part of the General Programming Boards category; Hi, everyone! The following code creates a linked list, and then free the memory for the list. I'm just a ...

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    16

    free the memory of linked list.

    Hi, everyone! The following code creates a linked list, and then free the memory for the list. I'm just a starter on C. Is the code correct? Thanks in advance!

    Code:
    #include <stdlib.h>
    #define MAX 3
    
    int main (void) {
      int i;
      struct list {
        char c;
        struct list *next;
      };
      struct list *start, *list_ptr;
      start = malloc(sizeof(struct list));
      list_ptr = start;
      for (i = 0; i < MAX; i++) {
        list_ptr->next = malloc(sizeof(struct list));
        list_ptr = list_ptr->next;
      }
      list_ptr->next = NULL;
      while (start) {
        list_ptr = start;
        start = list_ptr->next;
        free(list_ptr);
      }
      return 0;
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    It's correct in that the list is properly created and destroyed, yes.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    16
    Thank you! Now, I'm confident I understand some basic concepts in C.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linked list possible memory leak?
    By KBriggs in forum C Programming
    Replies: 17
    Last Post: 08-13-2010, 10:05 AM
  2. Anyone good with linked list.....I am not....
    By chadsxe in forum C++ Programming
    Replies: 11
    Last Post: 11-10-2005, 02:48 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Linked list probs
    By mouse163 in forum C++ Programming
    Replies: 5
    Last Post: 02-19-2005, 05:41 PM
  5. Help here with qsort!
    By xxxrugby in forum C Programming
    Replies: 11
    Last Post: 02-09-2005, 08:52 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21