/* MALLOC DEMO #2 Illustrates: use of malloc use of free passing pointers into functions the ** prototype (pointer to a pointer) scanf("%s", ... ) which is vulnerable to overflow */ #include #include #include #define MAX_WORD_LENGTH 30 void getWord(char *word); /* word is address of pointer (ptr to a ptr) */ int main(int argc, char *argv[]) { char *word; /* a.k.a pointer to String */ getWord(word); /* must pass word's address (why?) */ printf("Back from getWord. String is %s\n", word); free(word); word = NULL; /* NULL'ing after free'ing is a not a bad practice */ return 0; } /* Takes 1 arg: pointer to pointer to char (address of a char pointer) modifies the pointer whose address is in passed by dereferencing the pointer */ void getWord(char *word) { word = malloc(MAX_WORD_LENGTH * sizeof(char)); if (word==NULL) /* ALWAYS CHECK FOR NULL AFTER malloc */ { printf("malloc failed: Exiting Program!\n\n"); exit(EXIT_FAILURE); } printf("Enter a word (<%d chars): ", MAX_WORD_LENGTH); fflush(stdout); scanf("%s", word); /* DANGER: vulnerable to buffer overflow */ }