title: malloc/free() with error signal 6
body: <p>Here is a basic stack implementation code. However, it generates signal abort.</p>
  <pre><code>int *arr;
  int size = 2;
  int top = 0;
  
  int pop() {
  
      int i;
      if (top &lt;= size / 4) {
          int *arr2 = (int*)malloc(sizeof(int) * size / 2);
          for ( i = 0; i &lt; size; i++)
              arr2[i] = arr[i];
          free(arr);
          arr = arr2;
          size /= 2;
      }
      return arr[--top];
  }
  
  void push( int a) {
  
      int i;
      if (top &gt;= size) {
          int *arr2 = (int*)malloc(sizeof(int)*size * 2);
          for ( i = 0; i &lt; size; i++)
              arr2[i] = arr[i];
          free(arr);
          arr = arr2;
          size *= 2;
      }   
      arr[top++] = a;
  }
  </code></pre>
  <p>Here is the output:</p>
  <pre><code>*** glibc detected *** a.out: free(): invalid pointer: 0x0804a030 ***
  </code></pre>
  <p>and the debug data shows aborted sig 6 The interesting thing is  that it shows the line of free() but As 4386427 said, the problem is accessing out of bounds of memory while copying arr2 of size</p>
  <p><a href="https://i.stack.imgur.com/t5NiO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t5NiO.png" alt="enter image description here" /></a></p>
  <blockquote>
  <h1>0  0xffffe410 in __kernel_vsyscall ()</h1>
  <h1>1  0xb7e8a7d0 in raise () from /lib/libc.so.6</h1>
  <h1>2  0xb7e8bea3 in abort () from /lib/libc.so.6</h1>
  <h1>3  0xb7ebff8b in __libc_message () from /lib/libc.so.6</h1>
  <h1>4  0xb7ec5911 in malloc_printerr () from /lib/libc.so.6</h1>
  <h1>5  0xb7ec6f84 in free () from /lib/libc.so.6</h1>
  <h1>6  0x080484a0 in pop () at stacks_eng.c:14</h1>
  <h1>7  0x0804867e in main () at stacks_eng.c:55 (gdb) f 6</h1>
  <h1>6  0x080484a0 in pop () at stacks_eng.c:14 14                      free(arr);</h1>
  </blockquote>