1
shell_command(char gcommand[100]) {
    FILE *pipe = popen("ls", "r");
    char output[100];

    if ( pipe ) {
        fgets(output, sizeof output, pipe);
        pclose(pipe);
    }
    return output;
}

results in

program.c: In function ‘shell_command’:
program.c:42: warning: return makes integer from pointer without a cast
program.c:42: warning: function returns address of local variable

Ive googled around in two days with no success

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
user3760230
  • 29
  • 1
  • 5
  • Your function has no return value which apparently defaults to `int` as in pre-C99. Thus the first warning. The implicit-`int` should have given a warning before. For the second warning: See e.g. [here](http://stackoverflow.com/questions/9013402/i-am-getting-warning-function-returns-address-of-local-variable-in-c) or [here](http://stackoverflow.com/questions/12380758). And at least for the second warning I get a bunch of answers by searching for the message. – mafso Aug 15 '14 at 14:29

3 Answers3

8

You have declared your function as

shell_command(char gcommand[100])

which is interpreted by the compiler as

int shell_command(char gcommand[100])

while you want it to be

char* shell_command(char gcommand[100])

which would not work, because output is a stack variable and returning that is undefined behaviour, as your compiler tells you.

martin
  • 3,149
  • 1
  • 24
  • 35
3
  1. You've not specified the return type of the function, so the compiler assumes it returns an int, but you're trying to return a char *. Note that pre-standard C and C89 allowed this 'implicit return type'. C99 and beyond require the return type. Compilers still allow the code through because of the pre-standard legacy code.

  2. You're trying to return the local variable output, but that variable vanishes when the function returns. (You also return a pointer to an uninitialized variable if the popen() fails. And you ignore the gcommand parameter that's passed to the function.)

You should probably pass the buffer and its size to the function:

int shell_command(const char *gcommand, char *buffer, size_t buflen)
{
    FILE *pipe = popen(gcommand, "r");

    if (pipe)
    {
        char *result = fgets(buffer, buflen, pipe);
        pclose(pipe);
        if (result != 0)
            return 0;
    }
    return -1;
}

This returns 0 on success and -1 on failure, and (now) checks the return value from fgets() which could fail, but ensures that the pipe is closed regardless.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

Another way than returning char*. You are returning a local pointer variable. Instead pass a character array and copy output variable into that array using strcpy() Another method is to return character array and return type of function is char*