Search code examples
cstringfilepointersreturn

Why is char* foo() returning empty string?


I'm writing a C code that checks the number of occurrences of a word (entered by the user) in a text file, prints the count per line, and the total count on the screen, and compares the word with the last word of the file.

I have dedicated a function to fetch the last word called "Fetch", that fetches the word and returns it to the main function. then another function counts the occurrences, then a third function that actually compares the two strings using strcmp().

my problem is that the function char* Fetch() is seemingly returning empty strings for some reason. Note that I wanted to check where the problem actually is, so I tried to print the result inside the function on the screen instead of returning it to main() and it worked!!, so seemingly, the problem is the return statement, What could be the problem??

char* Fetch() called in main():

//step 3: fetch the last word in the file
Lword = Fetch();
printf("the last word is %s", Lword);

char* Fetch():

char* Fetch()
{
    char text[1000];
    fread(text, sizeof(char), sizeof(text), spIn);
    for(int i = 0; i < strlen(text); i++)
    {
        if(isspace(text[strlen(text) -1 -i])) //if space
        {
            return (text + (strlen(text)-i));  //return a pointer to the element after the space
        }
    }


}

declarations in main:

char Uword[20], *Lword;
int TotalCount;

Solution

  • You allocated a local char buffer text in function Fetch and store data into.

    When function Fetch returns, the buffer text will be released, then the content should NOT be used anymore.

    Function Fetch can be changed this way:

    char* Fetch(char *text, size_t maxlen, FILE *spIn)
    {
        fread(text, sizeof(char), maxlen, spIn);
        for(int i = 0; i < strlen(text); i++)
        {
            if(isspace(text[strlen(text) -1 -i])) //if space
            {
                return (text + (strlen(text)-i));  //return a pointer to the element after the space
            }
        }
        return text;
    }
    

    And can be called like this:

    FILE *spIn = ...
    char text[1000] = {'\0'};
    char *res = Fetch(text, sizeof(text), spIn);
    printf("the last word is: %s\n",res);
    

    Remember to use the text buffer when it's still valid.