Question

We have different ways to buffering a file contents (pass/return buffer to/from function and where/when to allocating memory). All of these functions work for me, but which one is the most standard way or recommended way?

1:

void buffering(FILE *file, char **buffer, int size)
{
    *buffer = (char *) malloc (size);
    read( input , *buffer , size );
}

call:

char *buf;
buffering( file, &buf, size);

2:

void buffering(FILE *file, char *buffer, int size)
{
    read( input , buffer , size );
}

call:

char *buf
buf = (char *) malloc (size);
buffering( file, buf, size);

3:

char *buffering(FILE *file, int size)
{
    char *buffer = (char *) malloc (size);
    read( input , buffer , size );
    return buffer;
}

call:

char *buf = buffering( file, size);

4: (tell me)

Was it helpful?

Solution 2

Allocating a buffer inside a function is considered bad practice. This is because the call to malloc (or new) is masked by the function call and the caller doesn't see the buffer allocation and is not clear to him (unless reviewing the function documentation) that he is responsible to free (or delete) the buffer.

In general there has to be an "owner" of the buffer. This owner has to be responsible to both allocating and freeing the buffer.

So to answer your question

void buffering(FILE *file, char *buffer, int size);

is the only one good. The others are bad for the reasons mentioned above.

OTHER TIPS

The most recommended way is encapsulating all buffering into an opaque structure like it is done with the fopen, fread, fclose family of functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top