title: Why am I getting "double free or corruption" with the following code?
body: <p>I am writing a simple program to make sure I fully understand how pointers in C work as I go through Harvard's CS50. Here is the code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void)
  {
      int *a = malloc(sizeof(int));
      *a = 5;
      printf("the address of pointer a is: %p\n", &amp;a);
      printf("the address that a is pointing to is: %p\n", a);
      printf("the contents of a are: %i\n", *a);
  
      printf("please enter a new value for a: \n");
      scanf("%i", a);
      printf("the address of pointer a is: %p\n", &amp;a);
      printf("the address that a is pointing to is: %p\n", a);
      printf("the contents of a are: %i\n", *a);
  
      int *b = malloc(sizeof(int));
      *b = 7;
      printf("the address of pointer b is: %p\n", &amp;b);
      printf("the address that b is pointing to is: %p\n", b);
      printf("the contents of b are: %i\n", *b);
  
      a = b;
      printf("setting a = b\n");
      printf("the address of pointer a is: %p\n", &amp;a);
      printf("the address that a is pointing to is: %p\n", a);
      printf("the contents of a are: %i\n", *a);
  
      free(a);
      free(b);
  }
  </code></pre>
  
  <p>It compiles w/o issues, but when executed, I get the following error: "<strong>* Error in `./address': double free or corruption (fasttop): 0x00000000018b7030 *</strong>
  Aborted"</p>
  
  <p>This problem goes away if I get rid of either the free(a) or free(b) statements, however valgrind reveals a memory leak:
  "==9626== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
  ==9626==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==9626==    by 0x4206AD: main (address.c:6)"</p>
  
  <p>I've looked through the other questions here and other websites that mention double free corruption, but still can't figure out quite what the issue is... I have a feeling that the answer is simple, and the issue probably lies in the statement "a = b", however I don't really get why I wouldn't be able to have one pointer point to a memory location that another one is pointing to, and then free the memory taken by both pointers...  </p>