0

getLine returns the array which store char of standard input. I try to print out the string in the array only get some other character, not the input. What is wrong with the function?

char *file_name;

file_name = getLine("enter the file name");
printf("%s\n", file_name);

char *getLine(char *question){
    printf("%s\n", question);
    char c, answer[100];
    int i = 0;
    c = getchar();
    while (c != '\n'){
        answer[i++] = c;
        c = getchar();

    }
    answer[i] = '\0';
    return answer;

}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
PMH
  • 43
  • 5
  • 3
    You are returning to a pointer to summat on the stack. This is destroyed at the end of the function – Ed Heal Mar 19 '15 at 15:05
  • http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – Lundin Mar 19 '15 at 15:46

3 Answers3

7

answer is an automatic local variable which does not exist once the function return and therefore a pointer to it will become invalid. Never return a pointer to an automatic local variable.

Pointer to static local variable can be returned

static char answer[100];  

or you can use dynamic allocation

char *answer = malloc(100);
haccks
  • 104,019
  • 25
  • 176
  • 264
  • is there any other way to obtains value of the array answer other than passing an external array? – PMH Mar 19 '15 at 15:07
2

Issue:

{
   char c, answer[100];
   //code
   return answer;       <--- Here
}

answer is local to getLine() with automatic storage. Once the getLine() function finishes execution, there is no existance of answer. Therefore, you may not return the address of the local variable.

Moral of the Story: enable compiler warnings and pay heed to them.

Workaround:

To achieve what you want you have to either

  • define answer as a pointer and allocate memory dynamically using malloc()/calloc(). Dynamically allocated memory has a global scope.

or

  • define the answer array as static.

The first approach is recommended (and my personal fav, too). Make a note to free() the allocated memory once you're done using that to avoid memory leak.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

Functions can return char * but not array in C.

answer is a local variable to function getLine() and returning local variable address leads to undefined behavior

char *getLine(char *question)
{
   char *answer = malloc(100);
   //Perform your stuff here
   return answer;//This is valid because the memory is on heap
}
Gopi
  • 19,784
  • 4
  • 24
  • 36