0

I wrote a func that gets a line from user.

Running it on windoes doesn't cause any warning.

But on unix i get the warning :

function UserIO_ReadLineFromUser() returns address of local variable -wreturn-local-addr

char* UserIO_ReadLineFromUser()
{
int i = 0, lineLen = 0;
char lineFromUser[MAX_INPUT_LINE_LENGTH];
fgets(lineFromUser, MAX_INPUT_LINE_LENGTH, stdin);
lineLen = strlen(lineFromUser);
lineFromUser[lineLen-1] = '\0';
while ('\0' != lineFromUser[i])
{
    lineFromUser[i] = tolower(lineFromUser[i]);
    i++;
}
return lineFromUser;
}

This is how i call it on main():

int main()
{
List* pHead = NULL;
char line[MAX_INPUT_LINE_LENGTH];
while (true)
{
    strcpy(line, UserIO_ReadLineFromUser());
    UserIO_ExecuteLineFromUser(line, &pHead);
}
return 0;
}

The program works but i want to get rid of this warning

a_beilis
  • 29
  • 7
  • The warning you see is most likely not because of `unix vs windows` differences. It is most probably because of the different flags set in the two different compilers you use. – Duck Dodgers Mar 19 '19 at 08:38
  • You are returning a pointer of a local variable from UserIO_ExecuteLineFromUser(). Simple solution: Since you are not using returned value from UserIO_ExecuteLineFromUser(), you can make its return type as void and remove "return lineFromUser;" line from it. – MayurK Mar 19 '19 at 08:39
  • Assuming you're using gcc, suppress this warning with `-Wno-return-local-addr`: Do not warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. – Alejandro Blasco Mar 19 '19 at 08:41
  • I get the error from UserIO_ReadLineFromUser. ill edit the post for it to be more clear – a_beilis Mar 19 '19 at 08:41

1 Answers1

3

You return variable created on stack. This is undefined behavior, cause stack is destroyed after function returns. You should allocate this variable on the heap, or pass to your function memory buffer

Alex
  • 1,047
  • 8
  • 21