functions returning char pointer

后端 未结 12 1311
醉梦人生
醉梦人生 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:41

    Never return a pointer to local variable. It may work in some situations, but in general you will have lots of problems with it. Instead:

    • document your function that it returns a pointer to allocated memory and that the returned buffer must be freed by the caller
    • add a buffer and a size argument, and fill in the buffer (this is what is generally done in the Win32 API)
    • if using C++, use std::string

提交回复
热议问题