Safe C
C with memory safety guarantees as strong as Rust.
Safe C is a fork of Clang with one flag, -fsafe-c. Code it cannot prove safe does not compile, or stops at run time instead of
corrupting memory. Its type annotations (_Owned, _Nullable, __counted_by) are macros from one header, so the same file is
still C for any other compiler.
Try it: in the browser, or brew install safe-c-project/tap/safe-c and then safecc file.c.
Or use it only as a checker: run safecc -fsyntax-only file.c in CI and keep building with gcc, MSVC or clang. That catches
the ownership and borrow errors; the run-time bounds checks need a safecc build.
Compared to Rust
| Rust | Safe C |
|---|---|
&T (never null) |
T * |
Option<&T> |
T *_Nullable, checked before use |
&[T] |
T *__counted_by(n) |
Box<T> |
T *_Owned |
Option<Box<T>>, Option::take |
T *_Owned _Nullable, _Take(place) |
&mut T / &T |
T * / const T *, for what may be freed or replaced (see below) |
&'static T |
T *_Static |
struct S<'a> |
struct _View S: locals and parameters only |
*const T |
T *_Unchecked, followed only in a _Trusted function |
a safe function with an unsafe body |
_Trusted |
unsafe { } |
__unsafe { } (does not lift ownership: that is _Trusted) |
enum with data, match |
union _Tagged_by(kind), plain data only |
Mutex<T> |
_Guarded_by(lock) |
What is different
- No lifetimes. A borrow lives in a local or a parameter. A returned borrow comes from the first borrowed
parameter; any other function has to be written another way. Rust needs
'afor what Safe C rejects. - Aliasing is allowed. Several mutable pointers to one object are fine. What ends them is a change to what the object owns: freeing, taking, replacing, or a call that may. So data races are not prevented.
- A function that can fail takes an owner and frees it, or hands it back as its
_Ownedresult. - No
Drop: free it by name. Forgetting to is a compile error;(void)_Take(p)lets it go on purpose. - No generics, traits or shared ownership (
Rc). A graph uses handles (pool.h), which know when they are stale, or_Uncheckedpointers and_Trustedfunctions. - Proved in Lean. The rules are proved sound in Lean 4 (safe-c-lean: 12,000 lines, no
sorry): a program that follows them has no use after free, double free, dangling stack access or out-of-bounds access; it runs or it traps. That clang enforces exactly those rules is tested (lit tests, four blind attacks, 10,394 corpus programs), not proved. Rust is in the same place: RustBelt proves a model of Rust, not rustc.
More
- Overview: what the code looks like, results on real CVEs and NIST's Juliet suite, the standard library, how to adopt it, and the limits
- Rules, annotations, library types, building
- Docs and playground: safe-c-project.github.io
Apache License v2.0 with LLVM Exceptions, like LLVM.