title: C: realloc() not functioning as expected
body: <p>If I have a variable, <code>str</code> that I would like to allocate memory to on the heap, I would use <code>malloc()</code> like:</p>
  
  <pre><code>char* str = (char*)malloc(sizeof("Hello"));
  </code></pre>
  
  <p><code>malloc()</code> is returning a <code>void*</code> pointer, which is the memory location where my memory is.
  So now, I can give it some data</p>
  
  <pre><code>str = "Hello";
  </code></pre>
  
  <p>So, the memory location is now full, with 6 bytes. Now, I want to increase its size, to contain the string <code>"Hello World"</code>. So, I use <code>realloc()</code>. According to <code>man</code>,  <code>void* realloc(void *ptr, size_t size)</code> will:</p>
  
  <pre><code>The realloc() function changes the size of the memory block pointed to by ptr to size bytes. 
  The contents will be unchanged in the range from the start of the region up to the minimum of 
  the old and new sizes. If  the  newsize is larger than the old size, the added memory will not 
  be initialized.
  </code></pre>
  
  <p>So I assumed that it will return a <code>void*</code> to the new, now bigger memory location, which I can now fill with my new string, so going on the same logic to <code>malloc()</code>:</p>
  
  <pre><code>str = (char*)realloc(str, sizeof("Hello World"));
  </code></pre>
  
  <p>But, this is where the problem is. This will cause:</p>
  
  <pre><code>*** Error in `./a.out': realloc(): invalid pointer: 0x0000000000400664 ***
  </code></pre>
  
  <p>And in valgrind</p>
  
  <pre><code>Invalid free() / delete / delete[] / realloc()
  </code></pre>
  
  <p>This suggests that there is something wrong with the pointer, <code>str</code>. So I decided to remove:</p>
  
  <pre><code>str = "Hello";
  </code></pre>
  
  <p>And it compiles fine, with the following code:</p>
  
  <pre><code>char* str = (char*)malloc(sizeof("Hello"));
  str = (char*)realloc(str, sizeof("Hello World"));
  </code></pre>
  
  <p>I am aware of the fact that pointer to <code>realloc()</code> must come from <code>malloc()</code>, but simply assigning data to it shouldn't cause <code>realloc()</code> to fail, which suggects that I am doing something completly wrong.</p>
  
  <p><strong> So, what am I doing wrong? </strong></p>
  
  <p>And here is the code that fails:</p>
  
  <pre><code>char* str = (char*)malloc(sizeof("Hello"));
  str = "Hello";
  str = (char*)realloc(str, sizeof("Hello World"));
  // str = "Hello World"; - this is what I would to be able to do.
  </code></pre>
  
  <p><strong>Note:</strong> This code is something I have stripped down from a much larger program, just 
  to demonstrate the problem I am having, so I have removed checks etc.
  Also, I am very new to C, so hence the really simple problem (sorry?), but after hours of work and research, I still can't figure out what I am doing wrong - It seems to work fine for everyone else!.</p>