Hi All.
I'm new to the forum. I'm having some issues with my program. I seem to be accessing memory that I shouldn't be (surprise, surprise!), but I can't see the problem. Keen eyes are welcome! Any help appreciated.
Sample input: Enter word for retrieval: the
Sample output: You entered: ' Uthe'
The program in its entirety counts the number of words, puts each word into a linked list and then searches the list from a text file input taken from the 'command prompt'.
/*dynamically expands array and inserts new letter at the end*/
char * makeword( char c, char *wrd, int wrd_len ) {
char *ch = &c;
/*alloc memory enough for existing word, new letter and '\0'*/
/*adapted from http://www.cplusplus.com/reference/clibrary/cstdlib/realloc.html*/
wrd = (char*)realloc(wrd, (wrd_len+1)*sizeof(char));
if( wrd == NULL ) {
perror("realloc returned NULL. Unable to allocate memory.") ;
exit (-1) ;
}
/*concatenate existing word with new letter*/
strncat( wrd, ch, 1 ) ;
return wrd ;
}
/*takes file pointer, reads (letter by letter) a word into a 'dynamic' char array*/
char * wordify( FILE * ifp, char *wrd ){
unsigned int c, prev_char = 0, wrd_len = 0 ;
/*make words until EOF is read*/
do{
c = getc( ifp ) ;
/*check if c is a letter. getc returns
EOF as an unsigned int, so we must check for it aswell*/
if( ( isalnum( c ) || isvalid( c, prev_char, ifp ) ) && c != EOF ) {
wrd = makeword ( tolower( c ), wrd, wrd_len ) ;
prev_char = 1 ;
/*increment counter when this letter is non-alpha but previous was alpha*/
} else if( !isalnum( c ) && c != EOF && prev_char == 1 ) {
prev_char = 0 ;
return wrd ;
}
}while( c != EOF ) ;
return wrd ;
}
void search() {
char *findthis = NULL, repeat ;
do{
printf( "Enter word for retrieval: " ) ;
findthis = wordify(stdin, findthis);
printf( "You entered: %s", findthis ) ; /*prints stdin with garbage infront*/
findthis = NULL;
printf( "\n\nSearch again? [y/n]: " ) ;
repeat = getchar() ;
}while( 'y' == repeat || 'Y' == repeat ) ;
}