title: How to free a linked list with pointers
body: <p>I was trying to free memory for a linked list iteratively. The list has a struct which looks like this, and in this linked list, I don't add a url if it's in this list.</p>
  
  <pre><code>struct Node {
      char *url;
      struct Node *next;
  };
  </code></pre>
  
  <p>Once done working with this linked list, I tried to free it, but got segmentation fault, I'm still in the way of learning <code>c</code>, I haven't got much clue of how to debugging such error other than directly searching for related topics. Referenced a few SOs <a href="https://stackoverflow.com/questions/33113510/free-memory-from-linked-list-in-c">this one</a>, <a href="https://stackoverflow.com/questions/6417158/c-how-to-free-nodes-in-the-linked-list">this one</a>  and <a href="https://stackoverflow.com/questions/4915369/how-to-free-a-struct-that-contains-only-pointers">this one</a>, still cannot figure out where it got crashed.</p>
  
  <p>Here's my code. Free feel to add comments if you think anything I missed in this implementation.</p>
  
  <pre><code>void url_push(struct Node *head, const char *url, size_t url_size) {
      struct Node *new_node = (struct Node *) malloc(sizeof(struct Node));
  
      new_node-&gt;url = malloc(url_size);
      new_node-&gt;next = NULL;
  
      for (int i = 0; i &lt; url_size; i++)
          *(new_node-&gt;url + i) = *(url + i);
  
      struct Node *current = head;
      while(1) {
          if (strcmp(current-&gt;url, new_node-&gt;url) == 0) {
              printf("Seen page %s!!!!!\n", new_node-&gt;url);
              free(new_node);
              break;
          } else if (current-&gt;next == NULL) {
  
              current-&gt;next = new_node;
              break;
          } else {
              current = current-&gt;next;
          }
      }
  }
  
  int main() {
      struct Node *head = (struct Node*)malloc(sizeof(struct Node));
      head-&gt;url = "/";
      head-&gt;next = NULL;
  
      char *url = "www.google.com";
      url_push(head, url, strlen(url));
  
      url = "www.yahoo.com";
      url_push(head, url, strlen(url));
  
      url = "www.google.com";
      url_push(head, url, strlen(url));
  
      url = "www.wsj.com";
      url_push(head, url, strlen(url));
  
      struct Node *current = NULL;
  
      while ((current = head) != NULL) {
          printf("url: %s\n", head-&gt;url);
  
          head = head-&gt;next;
          free(current-&gt;url);
          free(current);
      }
  }
  </code></pre>
  
  <p><strong>Edited:</strong>
  To reduce the confusions, I revised the struct. The purpose of using <code>strcmp</code> is to avoid adding a url that already seen.</p>