r/C_Programming • • 21h ago

three different approaches to an example in Fluent C book

Reading a post a few days ago, I looked for a book about C that had a Patterns approach along the lines of Design Patterns: Elements of Reusable Object Oriented Software and finally settled on Fluent C: Principles, Practices, and Patterns by Christopher Preschern.

The first chapter is about error handling where the author starts with a single function of a very simple file reader full of if statements and partitions it out into three different functions: allocation of resources, using the resources, deallocation of the resources. The resources are a file handle with access to provide read access to a text file and a large buffer to read the lines of text.

Here are three different approaches to managing the resources while using the resources is the same function for all three different approaches.

What are Pros and Cons of each? Is there one of the alternatives you feel is the most appropriate approach? Is there a fourth alternative you think better than these?

The first makeParser() and closeParser() functions are similar to Preschern's code except that what he does in two calls to malloc(), I do with a single call.

The second version is not allocating memory for the Parser variable but instead is using a stack allocation with a C99 Compound Literal to create a variable whose address is then passed into the second version of makeParser2().

The third version uses the same makeParser() as the first one however the closeParser3() function differs in that it is the responsibility of the caller to free the allocated memory.

An interesting point is that the three alternatives all use the same useParser() function.

#include <stdio.h>
#include <memory.h>
#include <stdbool.h>

typedef struct {
    bool   bValid;    // whether the Parser object is valid or not
    FILE* pFile;      // the file which is being processed
    void* pBuff;      // the address of the I/O buffer
} Parser;

#define MAX_FILE_BUFFER_SIZE  400


Parser* makeParser(const char* filename)
{
    Parser* p = NULL;

    // allocate the needed memory all in a single block to make free() easy.
    // this also ensures that all needed memory is available.
    p = malloc(sizeof(Parser) + MAX_FILE_BUFFER_SIZE);
    if (p) {
        // allocate resources and mark if valid when all
        // resources are allocated.
        p->pBuff = p + 1;    // the I/O buffer begins after the Parse struct.
        p->pFile = fopen(filename, "r");
        p->bValid = (p->pFile != NULL);
    }
    return p;
}

Parser* makeParser2(Parser* p, const char* filename)
{
    Parser  x = { .bValid=false, .pFile=NULL, .pBuff=NULL };

    if (p) {
        // allocate resources and mark if valid when all
        // resources are allocated.
        if ((x.pFile = fopen(filename, "r")) != NULL) {
            x.pBuff = malloc(MAX_FILE_BUFFER_SIZE);
            x.bValid = (x.pBuff != NULL);
        }

        *p = x;
    }
    return p;
}


int useParser(Parser* p)
{
    int iRet = 0;

    if (p && p->bValid) {
        while (fgets(p->pBuff, MAX_FILE_BUFFER_SIZE, p->pFile) != NULL) {
            printf(p->pBuff);   // the line will have next line when read as text
        }
        iRet = 1;
    }

    return iRet;
}

Parser * closeParser(Parser* p)
{
    if (p) {
        // free the resources and mark as invalid.
        if (p->pFile) fclose(p->pFile);
        *p = (Parser){ .bValid = false, .pFile = NULL, .pBuff = NULL };
        free(p);
        p = NULL;
    }

    return p;
}

Parser * closeParser2(Parser* p)
{
    if (p) {
        // free the resources and mark as invalid.
        if(p->pBuff) free(p->pBuff);
        if (p->pFile) fclose(p->pFile);
        *p = (Parser){ .bValid=false, .pFile=NULL, .pBuff=NULL };
        p = NULL;
    }

    return p;
}

Parser * closeParser3(Parser* p)
{
    if (p) {
        // free the resources and mark as invalid.
        // pBuff is part of the memory allocated for p so no free
        if (p->pFile) fclose(p->pFile);
        *p = (Parser){ .bValid = false, .pFile = NULL, .pBuff = NULL };
    }

    return p;
}


int main()
{
    const char fileName[] = "decompressed.txt";
    int iRetToss = 0;

    {
        Parser* p = makeParser(fileName);
        iRetToss = useParser(p);
        p = closeParser(p);
        iRetToss++;    // place for a break point to inspect p
    }

    {
        Parser* p = makeParser2(&((Parser) { .bValid = false, .pFile = NULL, .pBuff = NULL }), fileName);
        iRetToss = useParser(p);
        p = closeParser2(p);
        iRetToss++;    // place for a break point to inspect p
    }

    {
        Parser* p = makeParser(fileName);
        iRetToss = useParser(p);
        p=(free(closeParser3(p)), NULL);
        iRetToss++;    // place for a break point to inspect p
    }

    return iRetToss;
}
9 Upvotes

6 comments sorted by

4

u/matt9k 18h ago edited 18h ago

For my own sanity, I usually like to avoid malloc or free in main when I can. I like to make dedicated functions that handle the malloc and free of specific structs so I can make sure they are exactly parallel to each other - every malloc in the allocating function is freed in the closing/freeing function. Then in main I just use em and don’t need to think about it anymore.

For that reason I usually find myself doing option 1 here

1

u/Different_Panda_000 16h ago

That does make sense to have kind of bookends around a memory allocation in which a function is used to allocate the memory to use and its sibling to deallocate the memory.

What do you think of the use of a single malloc() to allocate both the Parser object as well as the buffer to be used with the file I/O?

Have you used memory arenas? They aren't really applicable to this particular example but for other places where temporaries created with a malloc() which are then destroyed only to be recreated again, an arena seems to make sense.

1

u/matt9k 16h ago

Malloc seems fine.

I haven’t tried using arenas yet, wanna learn about em soon.

2

u/scritchz 13h ago edited 13h ago

Unfortunately, I don't know the book you're referencing. But I'd like to give some opinionated critique:

Instead of make*/close*, I would name the functions create*/delete*. I'm simply more used to "create" than "make" for functions that both allocate and initialize.

Also, when returning a pointer from the close* function, it looks like the expected usage pattern is to assign this returned pointer to your variable. If that is the case, why not pass a double-pointer and set the variable's value inside the function? What would (or can) you do if variables outside the calling function have pointers to the then-freed struct? Personally, instead of expecting (or "requiring"?) any of these cases, I would instead return a boolean indicating whether the closing (or freeing) is a success, thus require the user to handle everything else (like unsetting dangling pointers) themselves by design.

I agree with u/matt9k, as in, I prefer to keep related functions at similar levels of abstractions, thus symmetrical. That means, if one of the functions does memory management, the other should, too. If one call to a make-function fully initializes, then a call to a close-function should fully finalize.

In approach 1, allocating the entire memory block like you do is nice and probably preferred, as it keeps all the data closer together, perhaps reducing cache misses or something. I don't know, I'm not a micro-optimizer (yet).

In approach 2, you have to pass a full struct to the make-function by its pointer. That means, the user must have the full struct definition available to them; the struct cannot be forward-declared and such struct pointers cannot be used as opaque handles. Not an issue if the parser implementation is part of the project, but (in my opinion) this should be avoided if the parser is developed as part of an independent library; unless the usage code is forwards compatible and the library is backwards compatible, e.g. by adding some way to identify what version the struct was made in, like how Windows (or Win32) often adds a struct member for the size of the struct of the current version and only deprecating old members instead of removing them, keeping struct sizes strictly growing with each following version.

Regarding your three approaches, a more neutral review:

In the close-function of approach 1, I don't see a reason to set something on the pointed-to struct, then freeing the pointer. Thereafter, reading through the pointer is UB, anyways. (At least I believe it is UB.)

The signature of the make-function of approach 2 seems misleading: As a user, I would expect that passing a pointer to a make-function initializes the memory behind that pointer. However, in your example, it seems the expected usage is to only use the returned pointer, whereas the passed pointer argument is only used to provide default values (which should only have one "valid" initial values; the function should know thus set these independent of any parameters). ((Different wording at the end))

As you already have to pass a struct pointer: I would allow the user to set the size of the buffer themselves, e.g. by passing the desired size in bytes to the make-function, or allocating the buffer out-of-scope and only passing its pointer to use for "making" the parser (in which case, freeing the buffer would similarly be out-of-scope for the close-function). As expanded upon in my last point of critique, this would require the user to know the struct definition, thus may not be desired by the implementation author (you).

In approach 3, the creation and deletion is asymmetrical. Each full make-function should be finalized by a full close-function, but isn't. Instead, the user is required to call free themselves.


((Here's the different wording, a bit more opinionated))

I don't like the way you called your make-function of approach 2: It looks like the function signature asks for a pointer to a struct you already have memory ownership of. So instead of passing some "default values" to the function, you should instead have your own struct (e.g. stack-allocated Parser p) and pass a pointer to it (e.g. makeParser2(&p, ...)). If that is the case, then it also doesn't make sense to return the pointer back to the user, as they would naturally have it accessible already if they were able to pass it in the first place. Instead, I would return a boolean to indicate success; regarding this, see one of my points of critique. Personally, I like passing pointers to self-owned blocks of memory, because it allows the user to decide for themselves how to allocate the necessary memory.

1

u/Different_Panda_000 4h ago edited 4h ago

Thank you for taking the time to not only review and analyze the source but to also do such a detailed writeup.

There are several things I'd like to discuss however let us start with the first one that stood out to me, your comment about the single allocation for both Parser struct and the I/O buffer. My purpose for this approach to have a single pointer to be concerned rather than two. One pointer to malloc(), one pointer to free(), one pointer to rule the buffer. I mainly do it to reduce the calls to malloc() and free() and to reduce the number of memory blocks created and to be managed. In this simplified example it's trivial however with more complexity, it's a way to have all the associated memory freed with a single call to free() rather than having to perform more than one call.

Returning the point is only a necessity with function closeParser2() and closeParser3() because it is up to the caller to free the memory for the Parser struct. In the case of closeParser3() the I/O buffer is part of the Parser struct and in the case of closeParser2() the Parser struct may be from malloc() or a stack variable depending on how makeParser2() is called. The role of makeParser2() is to allocate the I/O buffer which closeParser2() deallocates. Where the Parser struct comes from is unknown by makeParser2().

In the case of makeParser2() the Parser struct may be part of some other struct for instance a struct that contains the path name of the file as well as the Parser struct.

However as I look again at the code of closeParser2() with eyes made fresh by your critique, I think that returning a NULL pointer is an error. It should instead return the pointer that was passed in as this could be a source of a memory leak. In this particular instance since the Parser struct is a local stack variable created by the C99 Compound Literal, the orphaned memory will be reclaimed when the function returns but this would not be the case if it came from malloc().

You are correct that accessing a freed block of memory once free() has been called on it is UB. Initializing the Parser struct to a known state before deallocating it with free() is a habit of mine that has little utility, a holdover from single threaded applications with a primitive memory allocator. The original intent was to clear the memory to an initialized state erasing any stale data in the block. However there is no guarantee that any data set is not overwritten by the memory allocator or the block is not immediately given to some other thread.

Your critique of the function naming is reasonable. Frankly I'm not sure why I picked those names as they are not the names that the author of Fluent C used.

Concerning your comment referencing opaque handles, I'd like to point out that using an opaque handle is a design decision that may or may not be the intent of whoever is writing the code. An opaque handle is not always an appropriate decision choice. For example the iValid member of the Parser struct is available after a call to makeParser() to check the Parser was created and is ready for use.

To make a point, Microsoft is one of many API providers that publishes the layouts of structs such as the LOGFONT struct which describes a font to be used. While this simple example doesn't have such a complex description, it is also a toy, simple example to take a look at various approaches and design decisions for a function library to encapsulate some functionality. Using named initializers in this fashion provides a flexible interface in which some of the data members are initialized with specific values while the remainder default to zero.

As an addendum, consider this small change.

First introduce a new function, useParserX() that provides for a different return type, ParseReturn struct, for the useParser() function. This new function calls useParser() and returns not only the return value of useParser() but also the pointer to the Parser struct.

typedef struct {
    int iRet;
    Parser* p;
} ParserReturn;

ParserReturn useParserX(Parser* p)
{
    return (ParserReturn) { .iRet = useParser(p), .p = p };
}

Then we can chain these functions together as in:

    {
        ParserReturn x = { 0 };

        closeParser((x = useParserX(makeParser(fileName))).p);
    }

1

u/scritchz 3h ago

I have read your comment and would like to set aside some time to reply properly. Unfortunately, that will only be at the end of my day, at the earliest.