/* MALLOC DEMO #3 Illustrates: declaring an automatic array of pointers use of malloc function on that array use of the free function on that array passing pointers into functions the ** prototype (pointer to a pointer) */ #include /* string libraries etc */ #include /* input output */ #include #define MAX_WORDS 10 #define MAX_WORDLEN 50 /* F U N C T I O N P R O T O T Y P E S */ void loadArray( char **arr, char * infileName, int * count ); void printArray( char **arr, int count ); void freeArray( char **word, int count ); void fatal( char * errmsg); /* M A I N F U N C T I O N */ int main( int argc, char *argv[] ) { char *wordArray[MAX_WORDS]; /* a.k.a array of Strings */ int wordCount=0; if (argc < 2 ) fatal("Must enter a text input filename on cmd line. Exiting Program."); loadArray( wordArray, argv[1], &wordCount); /* pass only the array's name: it's already allocated */ printf("Printing wordArray:\n\n"); printArray( wordArray, wordCount ); /* again - need only pass array's name */ freeArray( wordArray, wordCount ); /* same here */ return EXIT_SUCCESS; } /* ------------------------------------------------------------------------ Takes 3 args: the name of an array of pointers a file name to read from and pointer to counter of words read in. Mallocs each pointer in the and copies a string into it. */ void loadArray( char **arr, char * infileName, int * wordCount) { char buffer[MAX_WORDLEN]; /* 49 chars plus a null terminator */ FILE * infile; infile = fopen( infileName, "r" ); if (!infile) fatal("Can't open specified input file. Exiting Program."); *wordCount=0; /* DANGER: fscanf of string vulnerable to overflow */ while ( (*wordCount < MAX_WORDS) && fgets(buffer, MAX_WORDLEN, infile) ) /* WARNING: fgets vulnerable to truncation but not overflow */ { arr[*wordCount] = malloc( (strlen(buffer)+1) * sizeof(char) ); if (arr[*wordCount]==NULL) /* ALWAYS CHECK FOR NULL */ fatal("malloc failed. Exiting Program."); strcpy( arr[*wordCount], buffer ); ++(*wordCount); } fclose(infile); } /* --------------------------------------------------------------------------- Takes 2 args: the name of an array of pointers, and a count of how many pointers have been malloc'd. Prints each string. */ void printArray( char **arr, int wordCount ) { int i; for(i=0 ; i