#include <stdio.h>
#include <stdlib.h>

char* strncat1 ( char* s1, char* s2)
{
   int i = 0;
   int j = 0;

   while ( s1[i] != '\0' )
   {
      i++;
   }

   while ( s2[j] != '\0' )
   {
      s1[i] = s2[j];
      j++;
      i++;
   }
   s1[i] = '\0';

   return s1;
}


char* strncat2 ( char* s1, char* s2)
{
   char* tempptr = s1;

   int i = 0;
   int j = 0;

   for ( ; *s1 != '\0'; *s1++)
   {
   }

   while ( *s2 != '\0' )
   {
      *s1++ = *s2++;
   }
   *s1 = '\0';
   return tempptr;
}

/*
There is a memory leak in the while loop.....
Each iteration the program allocates blocks of memory.
And at the end it appears that each block is correctly freed at the end of the while loop.
The problem, is that str3, which at the top of the loop points to a newly allocated  block of memory,
gets overwritten  with each strncat call.  The strncat actually returns a pointer to the first memory
block.  So when the free(str3) is performed, it is a duplicate of the free(str1).  
Each iteration, the third block of memory is lost.  This will never be recovered until this program 
terminates.  As this program runs, you can watch the virtual memory size of the process increase and
the amount of free space on the swap disk decrease by using the top command.
The program runs until the system can not allocate any more memory.
*/
int main()
{
   char* str1;
   char* str2;
   char* str3;
   char* tmp1;
   char *tmp2;

   while (1)
   {
     str1 = (char*) malloc ( sizeof(char) * 10000000 );
     if (str1 == NULL) {
       printf("Malloc 1 error.....\n");
       break;
     }
     str2 = (char*) malloc ( sizeof(char) * 10000000 );
     if (str2 == NULL) {
       printf("Malloc 2 error.....\n");
       break;
     }
     str3 = (char*) malloc ( sizeof(char) * 10000000 );
     if (str3 == NULL) {
       printf("Malloc 3 error.....\n");
       break;
     }
   
   strcpy(str1, "abc");
   strcpy(str2, "def");

   tmp1 = strncat1(str1, str2);
   printf ("1. New concatonated string 1: : %s, str2: %s, tmp1: %s \n", str1, str2, tmp1 );

   tmp2 = strncat2(str1, str2);
   printf ("2. New concatonated string 2:   %s, str2: %s, tmp2: %s \n", str1, str2, tmp2 );
   free(str1);
   free(str2);
   free(str3);
   
  }
}
