fe***********@g mail.com wrote:
My question is about if I should return char* or have a char* as an
argument. My basic premise for this function is to return a char*
buffer and the size of the buffer to the caller. I know that each of
the following works but Stylistic which would be the better approach.
A couple of questions:
1. The caller doesn't know how big of a buffer it's requesting?
2. What determines the buffer size?
Here are my two examples:
char* GetBuffer(long* size);
or
void GetBuffer(char* buff, long* size);
Thanks
Danny
My personal preference for writing allocators is to have the thing
being allocated as the return value: i.e.,
thing *p = newThing(/* any necessary inputs here*/);
To indicate an error, I'll return NULL, and (usually) provide a second
function to get information on the cause of the error.
char *buf = newName(10);
if (!buf)
{
int errcode = newNameErr();
switch(errcode)
{
...
}
}
I *typically* do not use output parameters in the allocator function; I
try to keep those kinds of things single-valued if I can, but sometimes
an output parameter is necessary. If the multiple outputs are
*logically* connected (I'd consider a buffer and its length to be
logically connected), then I'll create a new struct type and return a
new instance of it:
typedef nameBuf {
char *buffer;
size_t length;
} nameBuf_t;
nameBuf_t *newName()
{
nameBuf_t *newBuf = malloc(sizeof *newBuf);
if (newBuf)
{
size_t newLength = ... /* however buffer length is determined
*/
newBuf->buffer = malloc(sizeof *(newBuf->buffer) * newLength);
if (newBuf->buffer)
{
newBuf->length = newLength;
/* initialize buffer contents if necessary */
}
else
{
newNameErrorSet (MALLOC_FAILURE , newLength);
free(newBuf);
newBuf = NULL;
}
}
return newBuf;
}
int main(void)
{
nameBuf_t *name;
name = newName();
if (!name)
{
fprintf(stderr, "name allocation failed: %s\n",
newNameError()) ;
...
}
return 0;
}