functions returning char pointer

后端 未结 12 1267
醉梦人生
醉梦人生 2020-12-03 19:12

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

相关标签:
12条回答
  • 2020-12-03 19:42

    No, it is undefined behaviour. It just happens to work in your case, but may stop working at any time.

    0 讨论(0)
  • 2020-12-03 19:42

    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.

    0 讨论(0)
  • 2020-12-03 19:46

    The f1 function is returning a temporary (buff) which is freed when the function returns. You need to use malloc() inside the function.

    0 讨论(0)
  • 2020-12-03 19:47

    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.

    0 讨论(0)
  • 2020-12-03 19:51

    I'd suggest two possible solutions:

    1. 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.

    2. 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.

    0 讨论(0)
  • 2020-12-03 19:53

    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.

    0 讨论(0)
提交回复
热议问题