The common method is to allocate memory for the string using
malloc()
and returning a
char*
pointer to that allocated memory. The calling function is then responsible for freeing the memory:
char *SomeFunc()
{
char *buf = (char *)malloc(requiredSize);
return buf;
}
In some cases you can also use a
static char[]
buffer. Then return a
const char*
to that buffer. But you should know about the possible problems witch such functions (fixed size, not thread safe).
const char *SomeFunc()
{
static char buf[SOME_FUNC_STATIC_BUF_SIZE] = "";
return buf;
}
Another solution is passing the buffer and its size as arguments:
char *SomeFunc(char *buf, size_t size)
{
return buf;
}
With C++, use a C++ string type like
std::string
instead and return that. Then you don't have to care about freeing memory:
std::string SomeFunc()
{
std::string buf;
return buf;
}