c_mem_safety/README.md
2025-04-25 22:01:28 +02:00

1.2 KiB

RAII and defer macros for C

What?

Basically you can get everything apart nasty inheritance hiercheries:

  • Good perf post-OOP with structs, "methods" constructors, destructors
  • RAII for your resources (not just memory)
  • zig-style defer
  • no dependencies, just defer.h and handle.h (or just one if you need both)

Examples

Zig-style defer:

#include "defer.h"
...
    void *ram = malloc(n);
    defer {
        free(ram);
        printf("%d bytes freed\n", n);
    };

C++ / Rust style constructor and destructor:

#include "handle.h"

struct Vektor {
    int count;
    int *v;
}; handle(Vektor) {
    switch(state) {
    case HANDLE_CREAT:
        self->count = *(int*) data;
        self->v = (int*) calloc(self->count, sizeof(int));
        break;
    case HANDLE_DESTR:
        if(self->v) free(self->v);
        break;
    }
}

RAII (with scope closing destructors in reverse order):

int n; scanf(" %d", n);
creat(Vektor, data, &n);
printf("data.count:%d\n", data.count);

Compatibility

Ok this might be pain for you but this works only with gcc... At least it also works with C++ compilers so you can share your C codes later with C++.

LICENCE

CC-BY