C Returning char[] Warning “returns address of local variable”

ccompiler-warningspointersreturn

This is a portion of a homework assignment.

I am trying to read and return a single line of a file in my method getLine.

char *getLine(FILE *input) {
    char line[30];
    if(fgets(line, sizeof(line), input)!=NULL)
    {
        return line;
    }else{
        return NULL;
    }
}

This would seem to work from what I have been taught regarding pointers, however I am unable to remove the warning message warning: function returns address of local variable [enabled by default]. This warning is referring to the line return line;. My assignment requires that I have no warnings or errors when I compile. I don't see what I am doing wrong.

Most of the help I found suggested malloc-ing space for the line of text, but we haven't covered that in class yet even though I have done some in another class. Is that really the best way to do this? If so, would I be able to free anywhere in the program?

Best Answer

char line[30]; is an array with automatic storage duration. Memory where it resides is deallocated once the execution goes out of the scope of your function, thus pointer to this memory that you return becomes invalid (dangling pointer).

Trying to access memory, that has already been deallocated, results in undefined behaviour.

You can allocate your array dynamically and let the caller explicitly deallocate it:

char *getLine() {
    char* line = malloc(30);
    ...
    return line;
}

// somewhere:
char* line = getLine();
...
free(line);
Related Topic