|
|
Log in / Subscribe / Register

Memory-safe C code

Memory-safe C code

Posted Nov 16, 2025 0:26 UTC (Sun) by excors (subscriber, #95769)
In reply to: Memory-safe C code by alx.manpages
Parent article: Rust in Android: move fast and fix things (Google Security Blog)

>> while everything in C/C++ is unsafe by definition (as rust define it).

> It's possible to write memory safe APIs in C. It needs macro trickery, and combinations of modern language features.
>
> The main difference with Rust is that you need to opt-in to safety, instead of opting out of it. Also, there's no 'unsafe' keyword that distinguishes such code from the surroundings. However, once your code base does extensive use of these APIs, you essentially get a safe program.

That sounds exactly like what Rust calls unsafe. You could add the `unsafe` keyword to every function in your Rust program and then be careful to never call an "unsound" API (i.e. one that can actually trigger undefined behaviour when executed), and never do operations like pointer dereferencing that can trigger UB, and you'd be in the same situation as C code that only uses "memory safe APIs".

"Safe" in Rust basically means "the compiler can prove this won't trigger UB", and "unsafe" means "this won't trigger UB, and the compiler will believe that even if it can't prove it". (I think it helps to read "unsafe" as an abbreviation of "unprovably safe", not as a synonym for "dangerous"). The important distinction between safe and unsafe is the proof. C compilers don't do the proof, so C is always (in Rust's terminology) unsafe, no matter how well designed your APIs are.


The LWN site is currently under high scraper load, so comment display has been suppressed for anonymous users. If you are a human, you may read the comments by clicking the button below:

Note: you can avoid this step in the future by logging into your LWN account.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds