1

I'm following an rpcgen tutorial to make a small "remote proceedure call" utility where by a client sends a request to a server, then the server responds with a data formatted string. The return string is made by using strftime() char array and filling it with the formatted time. Then char array, either t or s is assigned to the *ptr, whoes address is returned as return(&ptr). What's curious, is that when I use the static char t, the function works and I'm able to receive the correct string. However if I use the non static char s[100] when i try to use the returned string, its a garbled mess or random characters and non characters. For the non-static case I don't write over it again, so why is it doing that? Also I'm not sure the implication of the function definition return value being a double pointer**, but I actually return a single pointer* with &ptr.

char **menuitem_1_svc(char *argp, struct svc_req *rqstp)
{
  struct tm *timeptr;
  time_t clock;
  static char *ptr;
  static char err[] = "Invalid Response \0";
  char t[100];
  static char s[100];

  clock = time(0);
  timeptr = localtime(&clock);

  //Use static char[] s or char[] t  both seem to work here
  strftime(s,100,"%A, %B %d, %Y - %T",timeptr);

  /*  This block is just an example.  ptr is only assigned to s or t.
  //This works
  ptr =s;

  //This doesn't
  ptr = t;
  */

  return(&ptr);
}
Kon
  • 4,023
  • 4
  • 24
  • 38
Frank
  • 459
  • 1
  • 5
  • 13

1 Answers1

5

This is happening because t is non-static (allocated on the stack), which means that when the function returns, the memory is freed and, by the time you reference that memory, it could be anything. This behavior is undefined.

This is a common mistake and you should never return pointers or references to local variables.

It works for static variables because those are allocated in the global memory and not on stack. Returning pointers and references to static variables, while works, is an anti-pattern and should be avoided.

Kon
  • 4,023
  • 4
  • 24
  • 38