I came across lot of functions returning char pointers in one legacy application. Some of them returning pointers to local character arrays. It seems to be causing crashes a
No, it is undefined behaviour. It just happens to work in your case, but may stop working at any time.
I would suggest changing these functions to take a pointer that it uses
void f1(char *)
That way every piece of code calling the function has to make a decision about where the memory gets written to, and to delete any memory that gets allocated.
The f1 function is returning a temporary (buff) which is freed when the function returns. You need to use malloc() inside the function.
No that's is not safe. Just calling strcpy can modify the stack enough to cause problems later because the return address and parameters might over-write the array.
I'd suggest two possible solutions:
Use a static char buff[20]
in f1
unless the function is called from multiple threads or the outside world stores the pointer beyond the strcpy.
Use return strdup (ptr);
and free
the pointer outside f1
. This is easier to use than malloc
(though technically the same). It's slower than 1. but thread safe.
No..its still not safe.
At the time you are doing strcpy(arr,f1());
, the pointer used as the 2nd argument is already pointing to an array that does not exist.