Since I can't return a local variable, what's the best way to return a string from a C or C++ function?

前端 未结 8 2093
失恋的感觉
失恋的感觉 2020-11-30 05:19

As a follow-up to this question:

From what I\'ve seen, this should work as expected:

void greet(){
  char c[] = \"Hello\";
  greetWith(c);
  return;
         


        
8条回答
  •  抹茶落季
    2020-11-30 05:36

    Returning malloc'd memory from a function as suggested by several of the other responses is just asking for a memory leak. The caller would have to know you malloc'd it and then call free. If they happened to call delete on it, the results are undefined (although probably okay).

    It would be better to force the caller to provide the memory for you and then copy your string into it. This way the caller is on notice that he/she needs to clean up.

提交回复
热议问题