//CPSC 360 Fall 2004  Quiz 8
//    This quiz is closed book/notes.
//    There is a memory leak in the main program.  Please fix it.  
//    Note:  the problem is not in either of the string concat functions.
//

#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;
}

int main()
{
   char* str1;
   char* str2;
   char* str3;

   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");

   str3 = strncat1(str1, str2);
   printf ("1. updated str1: %s, str2: %s, str3: %s \n", str1, str2, str3 );

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