title: C - Buffer on heap not lost after EXEC but saved on stack
body: <p>I was studying stack buffer overflows and I saw something that made me think. First of all the operating system is <strong>Damn Vulnerable Linux</strong> with kernel <strong>2.6.20</strong> and <strong>ASLR disabled</strong>.</p>
  
  <p>The fact is that I knew that when you call an exec function inside a C program, the memory in the heap and stack is zeroed and lost. But if I allocate a buffer in the heap (malloc) and then I pass a pointer to that buffer as argument to the program executed with the exec function, the data inside the buffer (in the heap) is saved on the stack. So at the end of the exec I have the buffer (that was in the heap before) in the stack.
  In order to make it clearer here's an example:</p>
  
  <pre><code>Program: bingo
  
  #include &lt;stdlib.h&gt;
  
  int main(int argc,char* argv[]){
      int i;
      char *buffer=malloc(600);
      for (i=0;i&lt;600;i++){
           buffer[i]='A';
      }
      buffer[600-1]=0;
      execl("./test","test",buffer,0);
  
      free(buffer);
      return 0;
  }
  </code></pre>
  
  <p>And test will be a simple program.</p>
  
  <pre><code>Program: test
  
  #include &lt;stdlib.h&gt;
  
  int main(int argc,char* argv[]){
      printf("Hello world\n");        
  
      return 0;
  }
  </code></pre>
  
  <p>Now if I debug the bingo program with GDB I can see that the content of buffer (all the As) that were put in the heap are actually copied on the stack during the execl function. So at the end of the execution of the program the heap is zeroed but the content of the buffer has been completely copied on the stack. My explanation is that this happens because this way the content of buffer will be made available to the executed program (test). I'd just like to know if this behaviour is normal.
  My doubt was: when I call the execl function I actually pass a pointer as argument to the executed program (test). 'Cause buffer is a pointer. So my (probably stupid) question is: shouldn't only the pointer be passed to the executed program and not also the content pointed by the pointer?</p>
  
  <p>Thank you</p>