C beginner here, I was given a homework assignment where we are to use gedit to design a program to read in file names from the command line and by designing a getNextWord method. We are to simply open each file one at and time and return the words, ignoring everything but alphanumeric characters (and converting uppercase letters to lower). The thing I'm hung up on is that my instructor gave us the strdup() function to help us out as well as isspace, alnum, etc. Anyways, after looking up strdup() on this site as well as C basics and the site and others there must be something I'm not understanding. My program compiles (I use gcc -Wall -pedantic -std=c99 words.c -o words) and it compiles with just a warning that strdup() is implicitly used. running the program with a few text files in the same directory has it print gobbly gook as if its running off the bounds of the heap, then giving a segmentation fault(core dump). I thought I was also giving it the right checks, such as putting \0 at the end of the character array before return strdup of the pointer, etc. Here is my code; I'm not expecting anyone to do my hw for me, maybe an observation would help as I have researched all day and cant find the problem. Thanks for reading this (its not showing but i included stdio, stdlib.h, string.h, ctype.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_SIZE 256
char* getNextWord(FILE* fd)
{
int index = 0;
int c;
char str[MAX_WORD_SIZE];
while((c = fgetc(fd)) != EOF){
c = fgetc(fd);
if (isspace(c)){
str[index] = '\0';
return (char*) strdup(str);
}
if (((index+1) != (MAX_WORD_SIZE-1)) && (isalnum(c))){
c = tolower(c);
str[index] = c;
index++;
}
else {
index++;
str[index] = '\0';
return (char*) strdup(str);
}
}
return NULL;
}
int main(int argc, char* argv[])
{
char** current = argv;
char* heapedString = NULL;
while (*current)
{
char* filename = *current;
FILE* fd = fopen(filename, "r");
if (fd == NULL)
{
fprintf(stderr,"can't read the file\n");
exit(-1);
}
while ((heapedString = getNextWord(fd)) != NULL)
{
heapedString = getNextWord(fd);
printf("%s\n", heapedString);
free(heapedString);
}
fclose(fd);
current++;
}
return 0;
}