title: Correct way to use malloc() and free with linked lists
body: <p>I am trying to understand malloc() better when it comes to linked list. Does this create memory for the pointer to the list as well as the fields inside of it?
  Such as:</p>
  
  <pre><code>  SomeStruct * someStructPtr = (SomeStruct *) malloc(sizeof(SomeStruct));
  </code></pre>
  
  <p>Alongside this, if I am trying to free this node AND the fields inside of it. Do I need to walk through all the fields (see code below). Does this just free the pointer (created from the line above) or does it free the pointer and and the fields.</p>
  
  <pre><code>free(someStructPtr);
  </code></pre>
  
  <p>For a more direct example. I have a struct of List and I'm trying to allocate space for this struct AND it's fields when it is created. I want to make sure I am creating, deleting, and using stdrup() correctly. My code is below: </p>
  
  <p>Struct Declaration:</p>
  
  <pre><code>typedef struct ListNode_st
  {
      char * str;
      struct ListNode_st * next;
  } List;
  </code></pre>
  
  <p>Create Node:</p>
  
  <pre><code>List * List_createNode(const char * str){
    List * listPointer = (List *) malloc(sizeof(List));
  
    //make sure there was enough memory
    if(listPointer == NULL)
      return NULL;
  
    //malloc for next
    listPointer.next = (List *) malloc(sizeof(List *));
    if(listPointer.next == NULL)
      return NULL;
    listPointer.next = NULL;
  
    //malloc for str
    listPointer.str = strdup(str);
    //make sure enough space for the string to be copied
    if(listPointer.str == NULL)
      return NULL;
  
    //return value
    return listPointer;
  }
  </code></pre>
  
  <p>Delete Node:</p>
  
  <pre><code>void List_destory(List * list){
    //base case -- (last item)
    if(list == NULL)
      return;
    //recurse case -- (there are more items)
    List_destroy(list-&gt;next);
    if(list-&gt;str != NULL)
      free(list-&gt;str);
    if(list-&gt;next != NULL)
      free(list-&gt;next);
  
    free(list);
  }
  </code></pre>