Search code examples
cfunctionreturn-valuelvalue

why return value of function can be assigned to?


Consider the following function:

 char *f()
 {   
 char *s=malloc(8);
 }
 main()
 {
  printf("%c",*f()='A');
 }

If I comment the line char *s=malloc(8); I get an error as if the assignment *f()='A' accessed invalid memory. Since I never return any variable why does above assignment work at all?

2nd question: 'A' is assigned to temporary variable created on return of function . So why can't ++a etc. be used as lvalue?


Solution

  • Assuming return values are passed in registers, the return value from malloc might still be there when returning from f(). By pure chance.

    When assigning to *f() you are not assigning to a temporary but to the memory returned from malloc. Assigning to ++a is totally different.