I have a function that is given two integers and returns a string. Right now I have this:
char* myfunc( int a, int b, int* len )
{
int retLen = ...
char* ret = malloc( retLen + 1 );
if ( len != NULL )
{
*len = retLen;
}
return ret;
}
However, most functions in the C library tend to do something more like:
int myfunc( char* ret, int a, int b )
{
...
return retLen;
}
You are then expected to allocate the memory for the function to fill. This allows you to do a bit more like choose where the string is allocated.
In this case though there is some maths required in the function to get the length, and there is no reason to have a buffer of any size other than the one needed. There is no upper limit on the size of the buffer (not one that is reasonable anyway).
What is considered good practice when returning a string whose length is dynamically found given the inputs?
A pattern I saw in kernel-mode programs is:
Sample:
The
needed_or_resultedcan be also used to transmit how much of the given memory was used in case of success.To be used like: