title: Deleting A Node From A Singly Linked List -- Using MALLOC/FREE
body: <p>I'm writing the oh-so common methods of deleted a node from a singly linked list, but I'm unsure if the way I'm deleting them (by using FREE()) is correct. I want to truly delete the node and free up the memory. I have provided the strut definition for Node as well as how Node structs are created. </p>
  
  <p>I understand in Java anytime nothing is pointing to data, it is cleaned up automatically. I figured for C, I have to use free, but am I using it correctly? For example below, when I 'free' current, am I able to make current reference something else after? What is the best way to do this?</p>
  
  <p>Thanks and I hope my question is clear!</p>
  
  <pre><code>typedef struct Node {
      int data;
      struct Node *next;
  } Node;
  
  struct Node* newNode(int value) {
      struct Node* node = (Node *)malloc(sizeof(struct Node));
      if (node == NULL) {
          // malloc fails. deal with it.
      } else {
          node-&gt;data = value;
          node-&gt;next = NULL;
      }
      return node;
  }
  
  void delete(int value, struct node *head) {
      struct Node* current = head;
      struct Node* previous = NULL;
  
      while (current != NULL) {
          if (current-&gt;data == value) {
              if (previous == NULL) {
                  current = current-&gt;next;
                  free(head);
              } else {
                  previous-&gt;next = current-&gt;next;
                  free(current);
                  current = previous-&gt;next;
              }
          } else {
              previous = current;
              current = current-&gt;next;
          }
      }    
  }
  </code></pre>