title: stack corruption in c
body: <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  #define SRC_BUFF_SIZE 32
  #define DST_BUFF_SIZE 8
  
  int tempfn1(char *p)
  {
      printf("p %p\n", p);
      return 0;
  }
  
  int tempfn(char *ip, int size)
  {
      char pttt[DST_BUFF_SIZE];
      printf("ip %p\n", ip);
      tempfn1(ip);
      // ERROR - copying more data to a local buffer of 4 bytes
  
      //memcpy(pttt, ip, size); // This will lead to stack corruption as     
                                // the size exceeds the size of destination
  
      // IDEALLY the copy should be done with min of size of destination buffer 
      // or source size rather than source size... 
      // anyways dest can hold only the size so it is better to crop the buffer 
      // than to crash due to overflow. 
      // proper call is as follows
      #define MIN(a,b) (((a) &lt; (b)) ? (a) : (b))
      memcpy(pttt, ip, MIN(size, DST_BUFF_SIZE));
  
      printf("ip %p\n", ip);
      tempfn1(ip);
      return 0;
  }
  
  int main()
  {
      char ip[SRC_BUFF_SIZE] = {0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 
      0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 
      0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 
      0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2, 0xe2 };
      tempfn(ip, SRC_BUFF_SIZE);
      return 0;
  }
  </code></pre>
  
  <p>This a sample program to avoid stack corruption. Is there any other function to check length of destination as well as the source inorder to avoid stack corruption?</p>