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 should be const, unless my_function is explicitly being given permission to write - for example - temporary terminating zero's or markers into the input string.
The second form is only valid if my_function calls "malloc" or some variant to allocate the buffer. Its not safe in any c/c++ implementation to return pointers to local / stack scoped variables. Of course, when my_function
calls malloc itself, there is a question of how the allocated buffer is free'd.
In some cases, the caller is given the responsibility for releasing the buffer - by calling free()
, or, to allow different layers to use different allocators, via a my_free_buffer(void*)
that you publish. A further frequent pattern is to return a pointer to a static buffer maintained by my_function
- with the proviso that the caller should not expect the buffer to remain valid after the next call to my_function.
In all the cases where a pointer to an output buffer is passed in, it should be paired with the size of the buffer.
The form I most prefer is
int my_function(char const* pInput, char* pOutput,int cchOutput);
This returns 0 on failure, or the number of characters copied into pOutput on success with cchOutput being the size of pOutput to prevent my_function
overruning the pOutput buffer. If pOutput is NULL, then it returns the number of characters that pOutput needs to be exactly. Including the space for a 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);