title: malloc() memory corruption
body: <p>I'm writing a program to read an arbitrary amount of lines from a file (where the first line is a header which I don't need), and dynamically allocate memory for them.</p>
  
  <pre><code>char buffer[350];
  char** addresses;
  char** temp;
  int i = 0;
  int check = 10;
  
  addresses = malloc(sizeof(char*) * check); /* let's start with 10 potential  addresses */
  
  if(addresses == NULL){
      printf("Unable to allocate memory.\n");
      exit(1);}
  
  fgets(buffer, sizeof(buffer), stdin); /* call this once to get past the header line */
  
  
  while(fgets(buffer, sizeof(buffer), stdin) != NULL)
  {
  
      if(i &gt; check) /* we need more memory */
      {
          temp = realloc(addresses,(2*check)*sizeof(char*)); /* double the memory we have */
          if(temp == NULL)
          {
              printf("Unable to re-allocate memory");
              exit(1);
          }
          else
          {
              addresses = temp;
              check *= 2;
              printf("reallocating to %d\n", check);
          }           
      }
  
      addresses[i] = malloc(strlen(buffer)); /* get memory for number of chars in each line */
      printf("2 %d\n", i);
      strcpy(addresses[i],buffer);
      i++;
  }
  </code></pre>
  
  <p>When I run it, I get a memory corruption error:</p>
  
  <pre><code>reallocating to 20
  reallocating to 40
  reallocating to 80
  reallocating to 160
  reallocating to 320
  reallocating to 640
  *** glibc detected *** ./a.out: malloc(): memory corruption:     0x0000000007721310 ***
  ======= Backtrace: =========
  /lib64/libc.so.6[0x37f0a71fbe]
  /lib64/libc.so.6(__libc_malloc+0x6e)[0x37f0a73dfe]
  ./a.out[0x400789]
  /lib64/libc.so.6(__libc_start_main+0xf4)[0x37f0a1d9f4]
  ./a.out[0x4005d9]
  </code></pre>
  
  <p>What could cause this?</p>