void my_function ( char *p_in_string, char *p_out_string, int *status )char* my_function ( char *p_in_string, int *status )int my_function ( char *p_in_string, char *p_out_string )
In all cases, the input string must be const, if my_function is not explicitly allowed to write, for example, the temporary completion of zero or markers in the input string.
The second form is only valid if my_function calls "malloc" or some other option to allocate a buffer. It is unsafe in any c / C ++ implementation to return pointers to local / stack variables. Of course, when my_function calls malloc itself, the question is how the distributed buffer is free.
In some cases, the caller is given the responsibility to free the buffer — by calling free() or, to allow different layers to use different allocators, through my_free_buffer(void*) , which you publish. Another common pattern is to return a pointer to a static buffer supported by my_function , provided that the caller should not expect the buffer to remain valid after the next call to my_function.
In all cases, when a pointer to the output buffer is passed, it must be mated to the size of the buffer.
The most preferred form is
int my_function(char const* pInput, char* pOutput,int cchOutput);
This returns 0 on failure or the number of characters copied to pOutput on success, cchOutput is the size of pOutput to prevent my_function pOutput buffer overflows. If pOutput is NULL, it returns the number of characters, which must be exactly pOutput. Including space for the null terminator, of course.
// This is one easy way to call my_function if you know the output is <1024 characters char szFixed[1024]; int cch1 = my_function(pInput,szFixed,sizeof(szFixed)/sizeof(char)); // Otherwise you can call it like this in two passes to find out how much to alloc int cch2 = my_function(pInput,NULL,0); char* pBuf = malloc(cch2); my_function(pInput,pBuf,cch2);