I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I’m not sure on how to do this safely..
const char *GetString() { std::stringstream ss; ss << 'The random number is: ' << rand(); return ss.str().c_str(); }
could the c string be destroyed when ss falls off the stack? I’m assuming so…
Another option may be to create a new string on the heap, but what is going to deallocate that?
const char *GetString() { std::stringstream ss; ss << 'The random number is: ' << rand(); char *out = new char[ss.str().size()]; strcpy(ss.str().c_str(), out); return out;//is out ever deleted? }
The same goes for pointers to other things as well as strings.
The first variant doesn’t work because you’re returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody’s overwriting the memory, making it very hard to debug.
Next, you can not return a const char* unless you return a pointer to a static string like this:
You second variant has the problem of returning memory allocated with new() into a C program that will call free(). Those may not be compatible.
If you return a string to C, there are 2 way to do that:
or:
depending on you memory handling policy.
As a rule, you can NOT ever return a pointer or a reference to an automatic object in C++. This is one of common mistakes analyzed in many C++ books.