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 *Ge
There are various methods, developed over time, to return a variable amount of data from a function.
strcpy()
strcpy_s()
snprintf
fread
gets
.qsort_s
qsort
fopen
->fclose
strdup
->free
std::shared_ptr
asctime
In general, whenever the user has to guess the size or look it up in the manual, he will sometimes get it wrong. If he does not get it wrong, a later revision might invalidate his careful work, so it doesn't matter he was once right. Anyway, this way lies madness (UB).
For the rest, choose the most comfortable and efficient one you can.
If you declare ss as static you can avoid the problem. This could be a good solution if your program runs on a single-thread enviroment.
Well obviously anytime you are returning pointers to memory allocated inside a function the deallocating must come externally, unless you are using garbage collection. If you don't want to do this, allocate a character buffer b efore calling GetString() and change the prototype to
int get_string(const char* buffer);
Then fill up the buffer. But returning a point to malloced data is fine.
You have to allocate the string on the heap if you want to safely return it, also allocate with malloc() i.s.o. new() when writing C functions.
When you return pointers (and, unlike in C++, in C you have no real choice many times), deallocation is always a concern. There isn't really a definitive solution.
One way of handling this I've seen in quite some API's is calling all function either
CreateString()
When memory needs to be deallocated by the caller, and
GetString()
when that's not an issue.
This is anything but foolproof of course, but given enough discipline it's the best method I've seen to be honest...