title: C Linked List - Create Nodes within Memory Block
body: <p>I am attempting to create a linked list within a pre-allocated block of memory. Put simply,</p>
  
  <ol>
  <li><p>I have an initial memory pool declared like so.</p>
  
  <pre><code>void *block = malloc(1000);
  </code></pre></li>
  <li><p>I created the head of a linked list from this pool:</p>
  
  <pre><code>struct node *root = block;
  </code></pre></li>
  <li><p>Let's say the memory address of the initial block is 100000. If I add a single linked list node of size 100, this just starts at 100000 (as it is the first node, sharing the memory address of the first block). If I add a second node of size 200, this should start at 100100 (at the end of the last block). And the next one would start at 100300, and so on.</p></li>
  </ol>
  
  <p>My method to add nodes to the list can be condensed as follows:</p>
  
  <pre><code>void add_node(int size) {
      new_node = malloc(sizeof(struct node));
      struct node *current = root;
      while (current != NULL) { //loop to get to the end of the linked list
          ...stuff (irrelevant to this question)...
          current = current-&gt;next;
      }
      new_node-&gt;value = size;
      current-&gt;next = new_node;
  }
  </code></pre>
  
  <p>The node definition is pretty generic:</p>
  
  <pre><code>struct node {
     int value;
     int free;
     struct node *next;
  };
  </code></pre>
  
  <p>The main method is as follows:</p>
  
  <pre><code>int main(void) {
      create_block(1000);
      add_node(100);
      add_node(200);
      print_all();
  }
  </code></pre>
  
  <p>And print_all simply iterates through and prints out the memory addresses:</p>
  
  <pre><code>void print_all() {
      printf("%ld (block start)\n", block);
      struct node* current = root;
      while (current != NULL) {
          printf("%ld (%d)", current-&gt;value);
          current = current-&gt;next;
      }
  }
  </code></pre>
  
  <p>However, when adding nodes with values 100 and 200, the memory addresses are as follows:</p>
  
  <p>25770205072 (block start)
  25770205072 (location of 100 node - this is ok)
  25769968848 (location of 200 node - not ok. This should be 25770205072 + 100)
  25770204784 (location of remaining 700 memory node - not ok. This should be 25770205072 + 100 + 200)</p>
  
  <p>Any clues for what I'm doing wrong? I tried a few different approaches without any luck.</p>
  
  <p>Thanks for your time! I appreciate any assistance very much.</p>