/* MALLOC DEMO #3 Illustrates: declaring an automatic array of pointers use of malloc on that array use of free on that array passing pointers into functions */ #include /* string libraries etc */ #include /* input output */ #include #define MAX_WORDS 10 #define MAX_WORD_LENGTH 30 void loadArray(char *arr[], char *infileName, int *count); void printArray(char *arr[], int count); void freeArray(char *word[], int count); int main(int argc, char *argv[]) { char *wordArray[MAX_WORDS]; /* a.k.a array of Strings */ int wordCount = 0; if (argc < 2) { printf("Must enter a text input filename on cmd line.\n"); exit(EXIT_FAILURE); } 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 0; } /* ------------------------------------------------------------------------ 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_WORD_LENGTH]; /* MAX_WORD_LENGYH - 1 chars plus a null terminator */ FILE *infile; infile = fopen(infileName, "r"); if (!infile) { printf("Can't open %s for input.\n", infileName); exit(EXIT_FAILURE); } *wordCount = 0; /* DANGER: fscanf of string vulnerable to overflow */ while ((*wordCount < MAX_WORDS) && fscanf(infile, "%s", buffer) == 1) { arr[*wordCount] = malloc((strlen(buffer)+1) * sizeof(char)); if (arr[*wordCount] == NULL) /* ALWAYS CHECK FOR NULL AFTER malloc */ { printf("malloc failed: Exiting Program!\n\n"); exit(EXIT_FAILURE); } 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 < wordCount; ++i) printf("wordArray[%d]: %s\n", i, arr[i]); } /* Takes 2 arg: the name of an array of pointers and a count of how many have been malloc'd. Visits each pointer in the array and frees the memory allocated to it. */ void freeArray(char *arr[], int wordCount) { int i; for(i = 0; i < wordCount; ++i) free(arr[i]); }