5 ms·
Such problem is pretty widespread and not limited by just structures, C-style strings are there too. For example: const char* getenv(const char* name); D
by c-smile 4y ago
Such problem is pretty widespread and not limited by just structures, C-style strings are there too.
For example:
const char* getenv(const char* name);
Do we need to free the string? And if "yes" then how? It is not realistic to provide free** for each such API function...
In Sciter API (https://sciter.com https://sciter.com) I am solving this by callback functions:
typedef void string_receiver(const char* s, size_t slen, void* tag);
const char* getenv(const char* name, string_receiver* r, void* tag);
So getenv calls string_receiver and frees (if needed) stuff after the call.
This is a bit ugly on pure C side but it plays quite well with C++ where you can define receiver for std::string for example and define pure C++ version:
std::string getenv(const char* name);
It would be nice for C to have code blocks a la Objective-C ( https://www.tutorialspoint.com/objective_c/objective_c_blocks.htm https://www.tutorialspoint.com/objective_c/objective_c_block... ), with them solution of returning data is trivial.
- juped 4y agoYou don't free the pointer returned by getenv(), because the environment variables are already in memory and getenv() is just giving you a pointer to one of their values. The most comfortable way to do a C API is to make the caller allocate space for return values (that aren't something simply copiable like int), and take a pointer to it as a parameter. The few standard library functions that malloc things are annoying, because you might not want to do that.
- c-smile 4y agogetenv() is just a sample. But even with it... it puts some limitation on potential API implementation and overall system performance. E.g. const char* user_password() cannot store the data anywhere, right? All that... > The most comfortable way to do a C API is to make the caller allocate space for return values That's even worse. How will caller know size of the buffer upfront? With the callback approach that is trivial - you get the size on call - no need to call the API function twice - for size of the buffer and then for real copy.
- saagarjha 4y agoYeah, it’s easy until someone calls setenv ;)
- coliveira 4y agoIn C the way to solve this is to look at the man page for the function and see what they say about memory allocation. There is no magic involved.
- c-smile 4y agoDocumentation solves just one problem: to free or not to free. But there are performance, security and other issues. What if it is significantly more performant for getenv() (or whatever) to fetch needed data using alloca (on stack, with fallback to heap/malloc)? Returning naked pointer is far from being flexible really.