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; } 
2
  • 3
    You are returning to a pointer to summat on the stack. This is destroyed at the end of the function Commented Mar 19, 2015 at 15:05
  • stackoverflow.com/questions/6441218/… Commented Mar 19, 2015 at 15:46

3 Answers 3

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

is there any other way to obtains value of the array answer other than passing an external array?
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 } 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.