functions returning char pointer

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

    No, you see buff[20] is only available inside the f1 function. To be precise, the memory is allocated on f1s stack.

    You need to create a new buff[20] on the heap using malloc and return a pointer to that memory from inside f1. Another way is to create buff[20] outside f1 (from the function which calls f1) and send it as an argument to f1. f1can then change the contents of the buffer and doesn't even have to return it.

提交回复
热议问题