Entries tagged C | Hugonweb Annotated Link Bibliography

Parse, don’t validate aka some C safety tips

https://www.lelanthran.com/chap13/content.html

You can even apply the popular parse don't validate idea to C!

The author also makes the point that C is a strictly typed language. Just because you can cast every pointer to (void *) doesn't mean misusing other types of pointers won't result in a compiler error.

This lets you make new types, as structs, and then to make functions that only operate on those. Then, you can make a parser accept plain old data, and return a pointer to a new instance of the struct on successful parse and to null otherwise. The fields of the structs can even be hidden from the header file.

Another nice tip is to make the destruction functions work like this:

struct name_t {
   char *name;
};
void name_del (name_t **name)
{
   if (name && *name) {
      free ((*name)->name);
      free (*name);
      *name = NULL;
   }
}

to avoid double freeing memory (by detecting the pointer is set to null).

The C programming language: myth vs reality [hidden strict fields]

https://www.lelanthran.com/chap9/content.html

Struct internals can be hidden from public consumers by hiding the struct definition in a source (not header) file like this:

Header File:

typedef struct MyType MyType;

MyType* init(int a, float b, ...);

Source File:

struct MyType { int a, float b, ... };

MyType* init(...) { ... };

The user of the header file doesn't even know how big a MyType is! They can't mess with it.