r/C_Programming • u/Different_Panda_000 • 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;
}
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
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 functionscreate*/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
freethemselves.((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.