title: Getting segmentation fault when indexing a 'mallocced' array
body: <p>I've been struggling with this one for a few hours now and I'm at a loss as to what's happening. This is the code for program.c:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;assert.h&gt;
  
  #define SPACE 32
  #define INITIAL 4
  
  typedef struct {
      char *town;
      char *country;
  } town_t; 
  
  typedef struct {
      int num_towns, current_size;
      town_t **towns_list;
  } index_t;
  
  int main(int argc, char *argv[]) {
  
      index_t town_index;
      town_index.current_size = INITIAL;
      town_index.towns_list = malloc(town_index.current_size * sizeof(*(town_index.towns_list)));
      assert(town_index.towns_list != NULL);
  
      printf("Step: %d\n", 1);
      town_index.towns_list[0]-&gt;town = malloc(4 * sizeof(*(town_index.towns_list[0]-&gt;town)));
      printf("Step: %d\n", 2);
      assert(town_index.towns_list[0]-&gt;town != NULL);
  
      return 0;
  }
  </code></pre>
  
  <p>On Linux this is how it runs:</p>
  
  <pre><code>./program
  Step: 1
  Segmentation fault
  </code></pre>
  
  <p>but on Windows it prints out </p>
  
  <pre><code>program.exe
  Step: 1
  Step: 2
  </code></pre>
  
  <p>as I'd expect, which really isn't helping. For the Linux output, however, clearly the first print statement is being executed but not the second, which would lead me to think that the line between is that one at fault. Particularly, I think doing <code>town_index.towns_list[0]</code> is causing me issues, but I cannot say why.</p>
  
  <p>This is a relatively complex data structure, so maybe I'm getting lost at some point. Basically <code>town_index</code> is meant to be a index struct that contains the current number of towns in <code>towns_list</code> and <code>current_size</code> which reflects the space currently available to save towns. It also contains an array of pointers to <code>town_t</code>s which contain the name and country as strings.</p>
  
  <p>I've tried to use Valgrind, but it's really not helping out much. Here's a <a href="http://pastebin.com/VCLV6AyS" rel="nofollow">Pastebin</a> for those who want to see.</p>
  
  <p>This is a simplified scenario of what I was experiencing in another program, so don't any mind magic numbers and whatnot. </p>
  
  <p>This is on VirtualBox Linux Mint 64-bit.</p>
  
  <hr>
  
  <p>Unrelated question, if anyone can: How do I get Valgrind to display the precise lines? I see that everywhere else online, but my output just tells me the folder in which the program and function is, which isn't much help.</p>