-1
#include <string.h>
#include <stdio.h> 

char *in() { 
    char a[10]; 
    scanf("%s",a); 
    return (a); 
} 

int main () { 
    char *a; a=in(); 
    printf("\n%s",a); 
    return (0); 
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

3

In your code,

 return (a);

is an attempt to return the address of a local variable. In the caller, any usage (attempt to access) of the address will cause undefined behavior, as the memory address is invalid.

After the function returns, the local variables inside the function will cease to exist, their lifetime expires. So, the addresses corresponding to those variables (objects) becomes invalid. As per C11, chapter §6.2.4

[...] If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

Note: That said, my personal addition:: return is a keyword, please don't make it look like a function.

Solution: You need to make sure that the lifetime of the variable of which the address is being returned, supersede the function scope, so you can either

  • use malloc() and family to allocate memory
  • use a variable with static storage.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Instead of repeatedly answering very common FAQs, how about starting to close them as duplicates instead? This question has 2 canonical duplicates: [Pointer to local variable](http://stackoverflow.com/questions/4570366/pointer-to-local-variable) when the OP doesn't know what they are doing and [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) when the OP knows that this is wrong but wants to know why it "seems to work". – Lundin Apr 13 '17 at 13:00
0

Do not return local variable pointer. Use global instead or static.

char *in() { 
    static char a[10]; 
    scanf("%s",a); 
    return (a); 
} 

int main () { 
    char *a; a=in(); 
    printf("\n%s",a); 
    return (0); 
}
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40