|
|
Log in / Subscribe / Register

Memory-safe C code

Memory-safe C code

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

About UB, in C we're now gaining an attribute that makes the behavior well-defined for signed overflow, but keeps diagnostics. Kees talked about it in the Linux Security Summit. I think that's a good approach.

Another thing is that C is removing many of the Undefined Behaviors. In the last year, the C Committee has transformed many UBs into constraint violations (mandatory diagnostic) or well-defined behavior, depending on the case. https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3529.pdf

About safety and pointers, I think it's not only possible, but easy. - Make sure all pointers have a provenance. This disallows things like (int *)42. (int*) 42; // diagnostic - Make sure all pointers are paired with a variable holding the number of elements in the array (with the only exception being functions that *read* null-terminated strings).

void f(int p[]);  // diagnostic
void g(size_t n, int p[n]);  // ok
- Assume that pointers with no specified length only have one element.
void h(int *p)  // p is a pointer to a single integer.  Pointer arithmetic not allowed.
{
    *p = 42;  // ok
    p++;  // diagnostic
}
- Make sure pointers are non-null before dereferencing.
void i(_Optional int *p)
{
    *p;  // diagnostic
    if (p != NULL)
        *p;  // ok
}
- Make sure pointer arithmetic is within the bounds specified by the number of elements.
void j(size_t n, int a[n])
{
    a[countof(a) - 1] = 42;  // ok
    a[countof(a)] = 7;  // diagnostic

    for (int i = 0; i < countof(a); i++)  // ok
        a[i] = 0;
    for (int i = 0; i < countof(a) + 1; i++)  // diagnostic
        a[i] = 0;

    a[42] = 0;  // diagnostic (42 not proved within [0,countof(a)).
}
--- These restrictions can't be used by every program, so some code might need to turn some of these off, but most programs could enforce all of this via a set of -Werror=... flags.


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