Hi, Following are two programs which behave differently for same situtaion. Code: #include<stdio.h> char *somfun() { char *t="pawan"; return t; } int main() { puts(somfun()); } Output : pawan Code: #include<stdio.h> char *somfun() { char t[]="pawan"; return t; } int main() { puts(somfun()); } output : garbage value Both variable inside function "somfun" are having local scope even after that first program is printing the value of t...how is it possible???????
Neither is correct, because in both cases t is on the stack and invalid after the function returns. This is correct, but you must remember to free the memory some time later otherwise this will leak memory: Code: char *morefun() { char *t=malloc(6*sizeof(char)); strcpy(t,"pawan"); return t; }