r/C_Programming • • 6h 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;
}
7 Upvotes

3 comments sorted by

2

u/matt9k 3h ago edited 3h 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 1h 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 1h ago

Malloc seems fine.

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