Reputation: 635
I am having some rather odd behavior with the MingW compiler for C.
I have a function, called getNextWord, shown here:
void getNextWord(FILE * pFile)
{
char * w = (char *)malloc(MAX_WORD_SIZE * sizeof(char *));
char * q = w;
char c;
while(c != ' ')
{
c = fgetc(pFile);
if(c != ' ')
{
*(w++) = c;
}
}
*(w++) = '\0';
printf("%s\n",q);
free(w);
}
For some reason, when I try to call this function twice in a row to print two words, it does not work. Weirdly enough however, if I put anything at all between the function calls, including printf, or fseek, then the function works as you would expect it.
This works:
int main(int argc, char** argv) {
FILE * pFile = fopen("doc.txt", "r");
getNextWord(pFile);
printf("a");
getNextWord(pFile);
fclose(pFile);
return (EXIT_SUCCESS);
}
This does not work:
int main(int argc, char** argv) {
FILE * pFile = fopen("doc.txt", "r");
getNextWord(pFile);
getNextWord(pFile);
fclose(pFile);
return (EXIT_SUCCESS);
}
Does anyone have any ideas why this is occurring?
EDIT: Thanks for the help, this is the fixed function:
void getNextWord(FILE * pFile)
{
char * w = (char *)malloc(MAX_WORD_SIZE * sizeof(char));
char * q = w;
char c;
do
{
c = fgetc(pFile);
if(c != ' ')
{
*(w++) = c;
}
} while(c != ' ');
*(w++) = '\0';
printf("%s\n",q);
free(q);
}
Sorry for all the errors there was in the original post, I'm new to C.
Upvotes: 0
Views: 66
Reputation: 206659
You're freeing the wrong pointer, leading to undefined behavior.
You need to free(q)
, not w
, since w
no longer points to what malloc
returned.
Upvotes: 2
Reputation: 539675
The local variable char c;
in getNextWord()
is not initialized, therefore
the initial test in
while(c != ' ')
is undefined behaviour. You should initialize e.g. as
char c = 0;
Upvotes: 2