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: 
What you're doing is returning a pointer to a local variable, which used to be allocated on stack.

Change your return statement to

```
return strdup(file);

```
You are returning a pointer points to the stack variable. When the function returns, the stack gets popped off. The stack variable no longer exists, the pointer become a dangling pointer. 

One solution is to allocate the appropriate amount of memory in the main function, and pass the pointer to the memory to the helper function.