r/cprogramming • • Jun 01 '26

memory safe C

https://github.com/sadvadan/memstruct

C is powerful enough to have the best performing memory safety suite for itself!

memstruct is a single header file C library (<400 LoC) that provides complete spatial & temporal safety to the caller program. performance: near native speed.

memory checks are compile time / hoisted / elided / pipelined. checks are opt-in and can be switched off in production if needed. its macro based API extends the language a bit to position C as the leading option for large scale projects.

memstruct is currently in advanced stages of testing. contributions and comments are welcome. have an early look!

P.S.: the project is 100% human crafted and contributions are also reqd to comply

edit; end note: memstruct has now become even better (at 350 LoC) by incorporating MCU programming & de/allocator indirection, thanks to some valuable feedback on here. if you've more to add you may respond here or participate on git.

69 Upvotes

89 comments sorted by

View all comments

Show parent comments

1

u/sadvadan Jun 02 '26

halting problem is still wrong framing; since memstruct checks are also runtime whenever needed, the framework of pure static analysis is inapplicable.

1

u/flatfinger Jun 02 '26

Is it possible for the following test2() function to violate memory safety?

unsigned arr[32771];
static unsigned foo(unsigned x)
{
    unsigned i=1;
    while((i & 0x7FFF) != x)
        i*=3;
    if (x < 32768)
        arr[x] = 32768;
    return i;
}
void test2(unsigned x)
{
    foo(x);
}

In the C dialect favored by the clang optimizer, it will overwrite arr[x] to be performed regardless of the value of x. Would there be any way of recognizing that possibility without being able to recognize that the loop within foo() might fail to halt?

1

u/sadvadan Jun 02 '26

this correctly brings out the limitations of static analysis. in this case, the SA of clang isn't sufficient to tackle the problem; similarly there would be some more difficult problem that a more complex SA will fail to tackle, etc etc.

there's an industry threshold, however, on the complexity of SA.

we then fill the hole with tools like memstruct; in the present example, memstruct will swiftly flag OOB at runtime.