Question: I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below

```
char* ListFiles(){
    FILE *fp;
    char file[30];
    char *f;
    if((fp=fopen("list","r"))==NULL)  
    {
        ...
    }
    while (!feof(fp))
    {
        fgets(file,50,fp);
    }
    fclose(fp);
    f=file;
    printf("%s",f); //get display!!!
    return f;
}
int main(){
      char *files;
      ...
      ...
      files=ListFiles();
      printf("%s",files); //nothing display!!
      sent();
}

```

However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work.

Answer: 
Follow [`George Skoptsov`](https://stackoverflow.com/users/1257977/george-skoptsov) recommendations. But If you don't have the [`strdup()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html) function,then use this:

```
char* strdup(const char* org)
{
    if(org == NULL) return NULL;

    char* newstr = malloc(strlen(org)+1);
    char* p;

    if(newstr == NULL) return NULL;

    p = newstr;

    while(*org) *p++ = *org++; /* copy the string. */
    return newstr;
}

```

And then:

```
#include <string.h> /* strlen() call */
#include <stdlib.h> /* NULL, malloc() and free() call */

/* do something... */

char* ListFiles() {
        /* .... */ 
         return strdup(f);
}

```

Or instead of `char file[30];` do a [`dynamic memory allocation`](http://en.wikipedia.org/wiki/C_dynamic_memory_allocation): `char* file = malloc(30);` then you can do `return f;` and it will work fine because `f` now is not a pointer to a local variable.
You're trying to display a string value char file[30] that is allocated on the stack (function stack). The content of this memory is not guaranteed after the method return. You should allocate it dynamically (for ex. malloc) or eventually use global value, or allocate it on the stack of the outer function (in your example main() function)