/* MALLOC DEMO #2 Illustrates: use of malloc function use of the free function passing pointers into functions the ** prototype (pointer to a pointer) */ #include #include #include #define MAX_WORDLEN 10 /* F U N C T I O N P R O T O T Y P E S */ void getWord( char **word ); /* word is addr of pointer (ptr to a ptr)*/ void freeWord( char *word ); void fatal( char * errmsg); /* M A I N F U N C T I O N */ int main( ) { char *word; /* a.k.a pointer to String */ getWord( &word ); /* must pass word's address (not value) */ printf("Back from getWord. String is %s\n", word ); freeWord( word ); word=NULL; /* NULL'ing after free'ing is a not a bad practice */ return EXIT_SUCCESS; } /* ---------------------------------------------------------------------------*/ /* Takes 1 arg: pointer to pointer to char (addr of a char pointer) modifies the pointer whose address is in the arg by deref'inf that arg. */ void getWord( char **word ) { *word = malloc( MAX_WORDLEN * sizeof(char) ); if (*word==NULL) /* ALWAYS CHECK FOR NULL */ fatal("malloc failed. Exiting Program."); printf("Enter a word (<10 chars): "); fflush(stdout); fgets(*word, MAX_WORDLEN, stdin); /* WARNING: fgets vulnerable to truncation but not overflow */ } /* ----------------------------------------------------------------------------*/ /* Takes 1 arg: a pointer. Frees the memory pointed to by the arg by passing the arg into the free function. Free does NOT modify the address it is given. Nor does it modify the contents of the memory at the address. It merely returns that memory to the heap. This is somewhat analagous to deleting a file. The OS merely marks that files as deleted (avail for re-use) but does not modify the data stored in it. */ void freeWord( char *word ) { free(word); } void fatal( char * errmsg) { fprintf( stderr, "\n%s\n", errmsg ); exit( EXIT_FAILURE ); }