cuser-inputfgetsfputs

'Control reaches end of non-void function' in C


I am trying to read the user's input. When I compile the program I get the message, 'control reaches end of non-void function [-Wreturn-type] }'.

char *read_line(char *buf, size_t sz) {
    while(fgets(buf, sz, stdin)) {
        fputs(buf, stdout);
    }
}

int main(int argc, char** argv) {
    char *buf;

    read_line(buf, 1024);
}

I want the program to take the user's input, press enter, and have their input printed back out to them. I gotta do it using the methods I have used (it's part of some homework).

I don't fully know what is going on under the hood of C, so it is just causes some many problems like this :).


Solution

  • For starters the function has undefined behavior because it uses an unitialized pointer.

    And the function shall have a return statement if its return type is not void.

    It seems you mean the following

    #include <stdio.h>
    
    void read_line( char *buf, size_t sz ) 
    {
        while( fgets(buf, sz, stdin) && buf[0] != '\n' ) 
        {
            fputs(buf, stdout);
        }
    }
    
    int main( void ) 
    {
        enum { N = 1024 };
        char buf[N];
    
        read_line( buf, N );
    }
    

    Or something like the following

    #include <stdio.h>
    
    char * read_line( char *buf, size_t sz ) 
    {
        if  ( fgets(buf, sz, stdin) && buf[0] != '\n' ) 
        {
            return buf;
        }
        else
        {
            return NULL;
        }
    }
    
    int main( void ) 
    {
        enum { N = 1024 };
        char buf[N];
    
        char *p = read_line( buf, N );\
    
        if ( p != NULL ) fputs( p, stdout );
    }