Is it correct to write a function that returns char *?
Something like this:
char * func()
{
char *c = new char[3];
strcpy(c, "hi");
c[2] = '\0';
return c;
}
int main()
{
char *c;
c = func();
//code using c
delete [] c;
return 1;
}
It works, but is it correct?
It is correct (assuming you meant
strcpyand notstrlen), but it must be very clear from the documentation of the function that it’s the caller’s responsibility to free the returned pointer, and what method does it have to use to free it (new=>delete,new []=>delete[],malloc=>free, etc). That is the “C way” of doing it.This relies on users of your function (including you after several months you wrote it) to read the documentation to get things right, so it’s quite error prone; also, in C++ there are several more complications that are not present in C (namely: exceptions) that make using raw pointers in these contexts not such a good idea.
That’s the reason why you normally should return classes that encapsulate resources (e.g.
std::stringin this case, and in general containers that manage the memory automatically) or ownership-transferring smart pointers, that also have the advantage of being exception-safe (which your code is not).This sounds extremely complicated, but in fact it’s not:
That’s it, no need to worry about allocations/deallocations and exceptions, all this is automatically handled by the
std::stringclass, so you can manage strings almost as they were builtin types.