/*
 *  ===========================================================================
 *  prog_savestring.c : Test dynamic allocation of memory for character strings
 *                                                                     
 *  Copyright (C) 1998 by Mark Austin and David Chancogne.
 *                                                                     
 *  This software is provided "as is" without express or implied warranty.
 *  Permission is granted to use this software on any computer system,
 *  and to redistribute it freely, subject to the following restrictions:
 * 
 *  1. The authors are not responsible for the consequences of use of
 *     this software, even if they arise from defects in the software.
 *  2. The origin of this software must not be misrepresented, either
 *     by explicit claim or by omission.
 *  3. Altered versions must be plainly marked as such, and must not
 *     be misrepresented as being the original software.
 *  4. This notice is to remain intact.
 * 
 *  Written by : Mark Austin 
 *  ===========================================================================
 */

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

int main( void ) {
char *saveString( char * );
char *cpName;

   /* [a] : Allocate memory for character string */

   cpName = saveString("My test string"); 

   /* [b] : Print contents of character string */
  
   printf("TEST STRING : \"%s\"\n", cpName ); 

   /* [c] : Free character string memory */

   free( cpName );                           
}

/* 
 *  ================================================================
 *  Version 1 of saveString() : Safe allocation of character strings
 *  
 *  Input  :  char *cpName     -- pointer to character string.
 *  Output :  char *cpTemp     -- pointer to allocated memory.
 *  ================================================================
 */ 

char *saveString( char *cpName ) {
char *cpTemp;

    cpTemp = (char *) malloc( (unsigned) (strlen( cpName ) + 1) );
    if( cpTemp == (char *) NULL) {
        fprintf(stderr,"saveString(): malloc failed\n");
        exit(1);
    }
    strcpy( cpTemp, cpName );

    return cpTemp;
}