|
|
Log in / Subscribe / Register

Memory-safe C code

Memory-safe C code

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

> [strstr] gives you a write access to the buffer than sometimes could and sometimes couldn't be modified.

That was solved already in C23. strstr(3) now returns QChar*, which is as qualified as the input.

<https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf>

> Even a simple call to strstr leaves you with a dilemma of validness of returned pointer (is its validity tied to needle or to haystack?)

I don't understand what you mean by 'validness'. I assume you mean provenance?

If so, I agree that GCC should add an attribute such as [[gnu::returns_derived_ptr()]], which would add that information to the API. There exist similar attributes already, so this wouldn't be very difficult.

[[gnu::returns_derived_ptr(1)]]
[[gnu::null_terminated_string_arg(1)]]
[[gnu::null_terminated_string_arg(2)]]
char *strstr(const char *haystack, const char *needle);

> Because these are, essentially, impossible to track without extra viral markup everywhere.

Yes, the attribute would fall under that "viral markup". libc is already full of those things. And I also use many of them in my own code.

> These problems are not impossible to track… but getting people to add (and correctly add!) such markup sounds like a more-or-less impossible thing to do.

If you show them a C code base that is as safe as Rust in terms of buffer overflows, and adding some attributes in some function prototypes is the only thing that needs to be done, I hope some programmers can be convinced.

About doing it correctly, the compiler should be able to tell if it's wrong when seeing the implementation. If the pointer isn't derived from the first argument in some path, it would of course diagnose.

> Essentially: it's hard but possible to add all these things to the language. But after you'll do that you'll need to rewrite almost everything anyway… and if you are doing it why not pick a nicer, more modern, language?

There's a difference between adding attributes to function prototypes and entirely rewriting the code.
These improvements can be done piecemeal, verifying that each change is self-correct, resulting in minimal logic bugs in the rewrite, compared to writing from scratch.


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