/* MALLOC DEMO #1 Illustrates: use of malloc function use of free function */ #include #include /* input output */ #include #define MAX_LEN 10 /* M A I N */ void fatal( char * errmsg); int main( ) { char *word; /* string */ word = malloc( MAX_LEN * sizeof(char) ); if (word==NULL) /* ALWAYS CHECK FOR NULL */ fatal("malloc failed. Exiting Program."); printf("Enter a word (<10 chars): "); fgets(word, MAX_LEN, stdin); /* WARNING fgets vulnerable to truncation but not overflow */ printf("you entered: %s\n", word); free( word ); word=NULL; /* NULL'ing after free'ing is a good practice */ return EXIT_SUCCESS; /* EXIT_SUCCESS is 0 in stdlib.h */ } void fatal( char * errmsg) { fprintf( stderr, "\n%s\n", errmsg ); exit( EXIT_FAILURE ); }