Hitesh Menghani
Hitesh Menghani

Reputation: 987

Returning local variables from function gives different output in two cases.

#include <stdio.h>
char* fun1()
{
  char *s="hello";
  return s;
} 
char* fun2()
{
  char s[6]="hello";
  return s;
}
main()
{
  char *str;
  str = fun1();
  printf("%s",str);//hello
  str = fun2();
  printf("%s",str);//garbage value
}

The output of code is - hello and some garbage. I am not understanding that though both variables in fun1 and fun2 are local to their respective function,why output is coming like that.Both function calls are returning address of local variables and addresses returned should contain garbage value which is not true in fun1 case as it is printing "hello".

Upvotes: 2

Views: 106

Answers (2)

kamituel
kamituel

Reputation: 35970

In the second function, you're returning pointer to the local variable.

As soon as fun2() invocation is completed, memory allocated to s[6] is being freed, so the pointer points to some invalid place in memory.

You could modify your code as follows:

char* fun2(char *s)
{
    strcpy(s, "hello");
}

char str[6];
fun2(str);
printf("%s",str);

Now the str[6] variable is allocated outside of fun2(), so this variable's memory is not being freed when fun2() exits.


Edit: note that above code isn't safe, as fun2() does not check or in any way control how many bytes it's writting into the memory.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182734

Because in the second case the object lives on the stack of fun2 while in the first case it lives in some fixed area. Once the invocation of fun2 ends it goes out of scope, i.e. it dies.

Both function calls are returning address of local variables

What is actually on the stack of fun1 is just a pointer, not the contents themselves. So you're returning a pointer to something guaranteed to live until the end of the program - a string literal.

Upvotes: 6

Related Questions