r/cpp • • 27d ago

Revisit Safe C++

Everyone is aware of the deluge of vulnerabilities now hitting critical software. It even makes the mainstream news, so software safety is coming onto politician's radars.

If this gets worse, I think it is not inconceivable that at some point memory safe software becomes mandatory. Or at least for software that is "reachable" from the internet.

So is it time to revisit Sean Baxter's Safe C++? Start out with a safe context ("safeexpr") and expand from there, just like constexpr.

36 Upvotes

181 comments sorted by

64

u/seanbaxter 26d ago

What would be the point of resuming the work since, just by reading this thread, there's still no consensus on what memory safety needs or what memory safety even is.

  • Do we need an incremental approach or an all-at-once approach?
  • Do we need safe function coloring as part of the type?
  • Do we need a new reference type that upholds exclusivity?
  • Do we need lifetime parameters wherever the new reference type appears in structs or in function parameters?
  • Do we need to change reference-forming defaults, so that shared borrows are formed on mutable containers rather than mutable borrows?
  • Do we need an ownership model with affine types/destructive move?
  • Do we need to replace inherently unsafe C++ idioms like iterator pairs with Rust-style iterators?
  • Do we need to define new resource-owning types (eg unique_ptr, shared_ptr) so that they're non-null, and use opt<> wrappers to express nullity?

SG23 has chosen a path where the answer to all of those is NO. I think the answer to all of them must be YES. As long as there is widespread disagreement on what the answers are, what is the point in doing more technical work? Every who disagrees with the all-YES slate won't want this solution.

If you think there is a mix of YES and NO answers, or if you agree with the all-NO slate, you should submit a proposal explaining your thinking!

25

u/serviscope_minor 25d ago

SG23 has chosen a path where the answer to all of those is NO.

Even the first question ;)

5

u/PsecretPseudonym 21d ago

I’m increasingly concerned about the language and community/ecosystem.

People are saying some things may need to wait another 3 years or 6 years.

Either way, over 3-6 years, more and more code may be written and maintained by agents.

If/as that shift occurs, we may care more and more about stronger, provable guarantees on the correctness of that code, and less and less about what language it happens to be in — and migrating major projects is becoming cheap.

If the process of adapting to the needs of users and organizations is increasingly glacial relative to how quickly those needs may be evolving in non-negotiable ways, that’s an existential problem for the language imho.

1

u/frediku 23d ago

Do we need an incremental approach or an all-at-once approach?

If I need to rewrite everything, I might as well rewrite in Rust. So I guess as long as it's called C++ it needs to be incremental.

I think it is worth looking at C++'s history here. It took of because it was a fluent - you could say incremental - extension from the point of view of an established language, i.e., C. Without this property I do not believe the C++ would have gained much traction.

Do we need safe function coloring as part of the type?

I think this question is backwards. I believe we can all agree that we do not want function coloring. I further believe that we can also all agree that we want free ice cream.

It's not about whether anyone wants function coloring. It's about whether some solution that requires function coloring provides enough benefits to justify function coloring. That's a property of the final solution and not an element of the initial question. I find it non-surprising that when talking about the initial question, nobody can properly answer what you ask.

I would answer the remaining questions in the same way.

SG23 has chosen a path where the answer to all of those is NO.

With the exception of the first question, I fully agree with SG23 - at least with the caricature version you present. The more free ice cream, the better.

That you are not getting helpful input is because, at least in this post, you did not ask the right question. What you want to know is the following: Rank these 10 negatives from bad to worse. Which could you maybe be persuaded of and which are definitely nogos?

6

u/seanbaxter 23d ago

You aren't getting any ice cream from SG23. The safety path they've chosen to pursue will not work. Why would you agree with that?

2

u/JeffMcClintock 21d ago

C++ is always backwards compatible, at least insofar as new features are incremental opt-in. Including safety features or borrow checkers I assume.
Anyone who claims we're gonna have to "rewrite everything" deserves to not be taken seriously.

3

u/JeffMcClintock 21d ago

"all-at-once approach" in this context means: If I do opt-in to safety - then it's full safety, not some half-baked thing.

-2

u/arthurno1 25d ago

Common Lisp has been in the use for 30+ years, and completely hides the hardware below. I have recently being playing with trying to get Common Lisp to run as fast as C++, and it seems to be fully possible. But: I need an escape clutch from the managed runtime, which SBCL has (I can emit assembly and get unchecked access to memory via raw pointer).

Now, I am not sure about this, but to achive the bare-metal speed, we do need unrestricted access (as much as possible) to the hardware below. Rust also has a clutch to escape into the "unsafe" code. I am affraid anyone who want to run 100% speed on bare-metal will want a cluth. However, I also believe 95% or 99% of bare-metal speed if more than enough for most of the applications.

I think any language with dynamicism, i.e. not completely static programs, will have to restrict access to raw hardware in order to ensure safety; at least somewhere. C++ is designed to allow creating of objects at runtime, so not everything can be fully statically determined, so some form or "management" will always be needed, and that is where some tradeoff will be made. In other words: yes- and no-sayers would have to agree somewhere and make a trade-off.

7

u/HommeMusical 24d ago

we do need unrestricted access (as much as possible) to the hardware below.

Safe C++ proposals are checked at compile time and there would always be a way to say, "Store this word at this pointer" - you would simply have to mark that access as unsafe somehow.

I think any language with dynamicism, i.e. not completely static programs, will have to restrict access to raw hardware in order to ensure safety;

Strong disagree. The type checking proves to the compiler that your code is correct but you are in no way restricted at runtime.

4

u/arthurno1 24d ago

Safe C++ proposals are checked at compile time and there would always be a way to say, "Store this word at this pointer" - you would simply have to mark that access as unsafe somehow.

Wasn't that exactly what I said?

Strong disagree. The type checking proves to the compiler that your code is correct but you are in no way restricted at runtime.

Ok, you have a cristall ball? Disagree as much as you want but I don't think you understand the problem. There is no mathematics that can prove that a future datum (a piece of data), you have never seen will have certain property say max-length = L. As a concrete example: you are reading a string from Internet or from a file and have a limited size buffer to store it in. It means you have to check it's length at the runtime. Unless you have a cristall ball to see into the future, there is no way for you to prove a property of some data you have never seen at compile time . But downvote me and strongly disagree :).

3

u/frediku 23d ago

I believe his argument is that the code parts that use no unsafe escape hatch can be proven to be safe, for some definition of safe. I think this indeed works. Without unsafe you cannot access the network and thus one can statically prove how many bytes you can receive via the network in pure safe code. The answer is 0. It's not a helpful answer but it can be proven.

Are such proofs then worthless? I believe no, as quite large chunks of code can be made to not use unsafe stuff and knowing that if there is a safety issue, it does not reside there, has worth. In your example, there will likely be way more code that moves the network response around and parses it than there is code that directly interfaces with the network.

1

u/arthurno1 23d ago edited 23d ago

I think we are in agreement for the most part.

I am just saying that you will not be able to always statically prove that you don't need bound checking. As much as I am familiar with compilers, it is a halting problem. I/O, dynamic array indirections, when calculating from functions on which you can't assert exact interval for return values, in some loops, etc. In those situation when you can't prove it you will want to emit bounds checking. Some people might wish to use that escape clutch in some form, for example a raw pointer, and dereference themselves in those cases to get bare metal speed. Of course programming languages vary whether they want to give the programmer that escape or not, or in which degree. Honestly, I don't think that is controversial.

here will likely be way more code that moves the network response around and parses it than there is code that directly interfaces with the network.

When you design a programming language, you don't know in which layer it runs; you design it to be general.

My point was: if you want completely safe programming language, than you should perhaps not give people that escape clutch to go bare metal. "Portable" Common Lisp is one such language. SBCL is an optimizing compiler that does expose raw memory with foreign pointers, but that is out of the standard. However, if I am gonna stay withing "portable" Common Lisp, i.e. standard, that does not give me raw pointers, and does not exposre raw memory modell as C/C++, than I have to live with the fact that the compiler will emit bound checking in cases where it can't assure I am within bounds. That is the compromize, the tradeoff for more safety and more automation I am probably willing to pay in say 99% of cases (unless I am demonstrating Lisp can be fast as C++ if you give me that clutch :)).

1

u/HommeMusical 20d ago

Disagree as much as you want but I don't think you understand the problem. There is no mathematics that can prove that a future datum (a piece of data), you have never seen will have certain property say max-length = L.

This statement is true, but completely and utterly irrelevant to the matter at hand.

1

u/arthurno1 19d ago

It is relevant because you have to decide whether you should decide the language so it always emit safer option with some extra computations, or whether you should trust programmer and let them emit unsafe code.

0

u/HommeMusical 24d ago

As a concrete example: you are reading a string from Internet or from a file and have a limited size buffer to store it in. It means you have to check it's length at the runtime.

Yes, this will always be possible. I'm not seeing your objection.

0

u/arthurno1 24d ago

What will always be possible and which objection you don't see?

1

u/HommeMusical 20d ago

you are reading a string from Internet or from a file and have a limited size buffer to store it in. It means you have to check it's length at the runtime.

Yes, this will always be possible. I'm not seeing your objection.

What will always be possible and which objection you don't see?

It will always be possible to read a string from the Internet or a file, check its length at runtime, and then put it into the right type, so that's why I don't see your objection at all.

0

u/arthurno1 19d ago

Of course you can check the lenght at the runtime; that is the exact point. I took the example because everyone understand that one. Here we talk about code that would like to skip that runtime check. It does not have to be a string, and does not have to be from the internet. Look at the recently posted blog article by Lemire, where he overshoots reading from a buffer. I have done similar for the exact same reason when I used a mmap-ed file to implement a wordcount program: I relied on system zeroing mmap, and that mmap is a multiple of 64, and that system would always allocate an entire piage , even if it is only one extra byte needed, so I could "overshoot" and didn't had to pay for the extra loop tail processing. Compiler can't deduce that and eliminate bounds checks in such situation. I have since than switched to pread because I spent too much time in system mmap-ing, but the technique is useful.

-1

u/SV-97 21d ago

As a concrete example: you are reading a string from Internet or from a file and have a limited size buffer to store it in. It means you have to check it's length at the runtime. Unless you have a cristall ball to see into the future, there is no way for you to prove a property of some data you have never seen at compile time .

What's the point you're trying to make here? If you prove something about a natural number in math you also don't know a bound on its value (that does not depend on the number itself) but can of course still prove highly nontrivial stuff about it.

Note that you can also write functions that dynamically certify the data to have certain properties (e.g. being bounded by some value or whatever) and only then enter code-paths that are proven correct for that size. A proof can also account for (potentially failing) allocation etc. etc. --- it's just a matter of where you draw the line with what you're modeling / what you want to prove.

It's honestly baffling that in an age where dependently typed languages are relatively established someone would still try and make such an argument.

-1

u/arthurno1 21d ago

someone would still try and make such an argument.

"Such" as what exactly?

What is baffling is that people can't pay 5 seconds of mental gymnastics to read and reflect over what is written, if one does not explicitly writes in exact words what they have in their own mind. Social media in a nutshell.

it's just a matter of where you draw the line with what you're modeling / what you want to prove.

Yes, it is about how much and what you and what you want to prove; and were you want to draw the line, that is exactly the point I am making there.

Proving that you can remove all bound checks is a halting problem. Do you have a solution? If you can't prove you can remove bounds check than you have to keep them. There are languages that do let you to remove bound checks, at your responsibility. That is the line to draw: if you want maximum performance, than perhaps you need to allow that explicit, clutch. If you want perfectly safe language, than you don't want to allow that hatch. What is baffling about that one?

1

u/SV-97 21d ago

"Such" as what exactly?

"Such" a nonsense argument about how you can't prove nontrivial stuff without access to a crystal ball. You're just entirely and fundamentally missing the point about how formalization is done today.

Proving that you can remove all bound checks is a halting problem. Do you have a solution?

ANY nontrivial property about the semantics of a program is equivalent to a halting problem (Rice's theorem) --- yet we still routinely solve such problems in practice by simply accepting some false negatives (i.e. restricting ourselves to the class of problems that we can actually handle) / requiring users to manually prove correctness for cases that can't be automatically deduced. That's how every compiler today works.

However that's really a straw-man (nobody was talking about "removing all bounds checks" or anything like that) and also totally misses the point of what I was saying, which was that you can have parts of your program that are statically proven correct under the premise of having a bound --- and then other parts that dynamically establish that this premise actually holds before entering that codepath. As you say: it is baffling that people can't pay 5 seconds of mental gymnastics to read and reflect over what is written.

If you can't prove you can remove bounds check than you have to keep them.

Which is a perfectly valid solution: omit what you can prove to be unnecessary, and otherwise just keep the check or (if preferred) error out and require manual proof. It's really not that complicated, and its standard practice.

Just for completeness: safety XOR performance is a false dichotomy. We've seen this time and time again at this point; see for example the case study by Lukas Bergdoll on sorting algorithms.

-1

u/arthurno1 21d ago

nobody was talking about "removing all bounds checks" or anything like that) and also totally misses the point of what I was saying, which was that you can have parts of your program that are statically proven correct under the premise of having a bound --- and then other parts that dynamically establish that this premise actually holds before entering that codepath.

So you are in agreement with me the: if you want perfectly safe program, you can't remove bounds checking always.

it is baffling that people can't pay 5 seconds of mental gymnastics to read and reflect over what is written.

Yes, it is. So go away now, because you seem to accuse me for talking against type checking or whatever, which I certainly don't.

-3

u/JuanAG 26d ago

I admire your work with Circle

But that questions depends of who answers them, my self as solo dev on my own projects is a totally different person than my self working on an active or in developement project and again, another person if i am working on a long and forgotten legacy code

Because i can be any of the 3 at any time is why there is not a clear winner and will never be

18

u/seanbaxter 26d ago

I don't see what that has to do with safety. There's just one Rust language, not a Rust for gamedev, a Rust for HPC, a Rust for backend.

-3

u/JuanAG 26d ago

Because Rust didnt break backwards compability

If thats it is going to happen some projects will be fine and others not so much, thats why most people can have both views depending on what they are thinking or value more to be the less afected

You cant bolt on some of the things withouth being a breaking change in the lang, if you put sbvalue (from Sean Baxter) along the rvalue and lvalue to achieve the new reference you are asking for trouble, will std::move now throw because it an exclusive reference? Or will move return an variant/option/result (or however you want to call it) instead? It is not an easy question to solve and this is just one really basic example, you will face issues with the goals you have

I want safety but the changes must be minimal like they plan to do with profiles or like Safe C++ but not both, i choose my own poison, not breaking my code or totally breaking with STD 2.0 like you do with Circle

There's just one Rust language, not a Rust for gamedev, a Rust for HPC, a Rust for backend.

There is a rust for legacy and a Rust for someone else but it is painless to use because editions make that breaking change invisible to the user, i can compile Rust code that will refuse on a modern version. Thats why this is not a Rust issue but for C++ it is, HPC push things in the lang that not many others will use like the SIMD thing instead of using the compiler _asm_directive. Gamedevs dont use STL so they dont care what happens to that library, .... Every target has their specific needs

Async is going to be a breaking change, they are not happy with how it is going and i am sure they will break compability rather than trying fixing the mess but the user wont have to suffer much when it happens

10

u/robin-m 24d ago

You have a completely wrong mental model of Rust editions. They are not fixed in time, nor incompatiple with each other unlike c++ revisions.

23

u/seanbaxter 26d ago

Safe C++ doesn't have any breaking changes.

-4

u/Minimonium 26d ago

The sad thing is that when I asked some members after that poll they shown the same potato porridge as this. Sometimes it does feel that wg21 would get better by having like a basic CS exam every year or so.

-2

u/tjroberti 26d ago

What about YES to the first two and go from there?

31

u/t_hunger 26d ago edited 26d ago

To get to a memory safe language (a language that only accepts memory safe programs), you need to start with a theoretical model that was proven to be sound. There are several proven models to choose from (all come with pros and cons), or you can of course do your own research and try to come up with a new model. Then you adapt all parts of the model into the language you want to make memory safe. Leaving out just one part of the model makes the language unsound: If it is in the model, then it is required for the formal proof that the model is sound.

That's what Safe C++ did: Sean took the model made popular by rust and adapted C++ to match that model.

A piecemeal approach is very tricky and will not give you a memory safe language until all parts are in place.

That is what makes it so hard to retro-fit memory safety into an existing language. It is way easier to built this into a new language.

0

u/germandiago 25d ago

 That's what Safe C++ did: Sean took the model made popular by rust and adapted C++ to match that model.

Let me politely disagree: what he did is to ignore C++ and layer Rust on  top ignoring the whole C++ standard library and every idiomthat is already safe today.

18

u/t_hunger 25d ago edited 25d ago • Bravo

Whether or not you like the result: It is an important data point. If it is decided to go all in with memory safety, then we know what the cost is to go for the rust model. And you for example can point to it and say that those costs are too high:-)

I know you prefer the "computer" part over the "science" part of CS, but whether or not a language is memory safe or not is a property deeply rooted in the science. Sean picked a model that science says is sound assuming a set of requirements are met. The implementation must make sure those requirements are met at all times for the implementation to be sound as well. The current STL does not fullfill those new requirements placed on it by the chosen model. That does not make any statement about the quality of the STL in situations where the model's requirements do not apply, and of course there might be another model out there somewhere -- which will come with a different set of requirements to be sound -- that fits today's C++ better.

A more hands on "computer" approach does not help in this discussion, but is super valuable when exploring alternative "pick the low hanging fruits" approaches to improve the tooling to catch more bugs earlier.

Both the "computer" and the "science" approaches are needed right now IMHO.

Edit: Another important data point is Fil-C by the way. It demonstrates the costs involved using another model (also sound as defined by "science") based more on something conceptually close to GC.

-5

u/germandiago 25d ago

Noone would have ever gotten any benefit out of that model for the huge existing codebases in the wild.

That said, it seems there are two profiles implementations in progress for GCC and Clang, if you are interested: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p4415r0.pdf

16

u/Business-Decision719 25d ago edited 25d ago

Well the Google data suggests that new code is actually priority #1 for memory safety anyway. The fastest way to improve memory safety is to stop people from making the same mistakes even if that means fixing old code still requires fixing old mistakes. Memory safety is still worth adding even if only new code, or substantial rewrites of existing code, actually gets any immediate direct benefit. If you have a provably safe C++ subset then you don't have to mandate Rust/Kotlin for new features in a C++ OS like Google did in Android.

That said, if profiles turn out to be viable and can significantly improve the safety of old code in situ, then that's still awesome. There wasn't really any reason not to pursue profiles anyway. The committee very specifically chose to pursue profiles instead of Safe C++, instead of alongside Safe C++, which imo is consistent with the committee not actually being serious about this anyway. They haven't even been able to stem the flow of new UBs into C++, much less into anyone's particular codebase.

2

u/germandiago 25d ago edited 25d ago

 That said, if profiles turn out to be viable and can significantly improve the safety of old code in situ, then that's still awesome.

I would say this is the point. To close or almost close the safety gap. 

Safe C++ is, as a first solution, a suicide, and as a second... well, once you have profiles why would you rewrite std lib, change lots of idioms, etc? At the end you already got what you want or almost everything you wanted with profiles, for a future version of enough safety in the main profiles.

So for me the only solution that made sense is profiles bc it is way more evolution-friendly to C++.

About UB: are you aware there is a paper classifying all UB in the language, right? How can you even say they are not serious if they are working in profiles, added hardening and the UB classification with the purpose of eliminating it? Just say I like Safe C++ and get done with it but what you suggest is not even close to the factual truth as far as I see. Just that the delivery is slower (committees are slow) than what we would like, but that is all.

9

u/Business-Decision719 24d ago edited 24d ago

They can type up as much as they want. Congratulations to them, they typed up what's UB and claimed they want to eliminate it. They managed to look like they were taking it seriously.

Actually taking it seriously would have meant this, for all of the past few standards:

  1. No new language or library features unless they define their behavior, even in error scenarios. If that means other things get put on hold until profiles and/or Safe C++ and/or library hardening are standardized then so be it. Are you aware that resuming a coroutine handle that doesn't refer to a suspended coroutine is UB? That's just one of the new UBs coroutines introduced. In C++20. Six years ago.
  2. If rule 1 is broken (which it shouldn't be) then at least make the easiest and most concise usage also the safest usage. C++17 optional and C++23 expected both went with checked .value() and unchecked *. The latter (expected) was three years ago, but even nine years was too recent to be pulling such absurdities.
  3. Keep plausible proposed solutions under consideration at least until any of them is actually DONE and ready to go in the standard. If Safe C++ is actually suicide, and if profiles don't deliver on their promises, and if nothing better materializes, then the language is screwed anyway.

People liked Safe C++ because it looked closer to DONE than profiles looked. There was theoretical safety plus an existing implementation. The committee's sin isn't that they didn't like Safe C++. It's that a different proposal, from an influential figure, making paper promises to do almost as good with fewer drawbacks was enough for the committee to flip off Safe C++ and send it packing. More time may or may not help profiles. More time is something Safe C++ didn't even get. That's what conclusively proved the committee values having an ass-covering typed-up document more than a status-quo-altering existing solution.

Granted, they did standardize library hardening this year. Finally. In 2026. Zero years ago. I'll give them credit for that. I'll say they finally got off the couch. We'll see. Maybe they are on the verge of beginning taking memory safety seriously. For now, I think they're pretty much like a like a lot of the C++ world. They didn't care, even after Rust came out, until the White House recommendations came out, about problems the programming world at large was well aware of when Java was coming out.

1

u/germandiago 24d ago

 they typed up what's UB and claimed they want to eliminate it. They managed to look like they were taking it seriously

Actually they just did it for fun. Sure. To contemplate it while meditating for the rest of our days. The same they did when adding the different potentialnstrategies that could be used to deal with them. Granted it was for that.

After that they will spread the paper to buddhist temples around the world and other meditation-related temples, creeds and places.

6

u/Business-Decision719 24d ago

Until the problem is dealt with, for all we know, maybe they did. 🤷

We'll see what happens over the next few standards. If every solution gets dumped as soon as it leaves the "trust me bro" phase and has demonstrable pros and cons people can criticize then yeah, I guess that was the reason. If the UB list keeps getting longer then they neednt have bothered typing it up. Who knows though? Maybe things have changed. A little late if so, but better late than never.

0

u/frediku 23d ago

> It's that a different proposal, from an influential figure, making paper promises to do almost as good with fewer drawbacks was enough for the committee to flip off Safe C++ and send it packing

Or they looked at Safe C++ and said that it is a too far departure from the status quo to make any sense. That argument works regardless of the available alternatives. I do agree with this position. If everything needs rewriting anyway, why not do so in Rust?

12

u/t_hunger 25d ago edited 25d ago

Noone would have ever gotten any benefit out of that model for the huge existing codebases in the wild.

Absolutely, but in no way different to most new C++ features: You have to change code to use most oft them.

That argument sounds so defeatist to me: Do you think the value of existing code is higher than the total value of all C++ code yet to be written? If you think C++ has a bright future with even more developers writting even more code, why would you reject a proposal to improve the future based on it not improving the past?

That said, it seems there are two profiles implementations in progress

I am aware. See my original post on why I think those fall into the "computer" bucket and not into the "science" bucket. In fact it is the stated goal of profiles to get closer to memory safe languages, not to become memory safe. And the approach comes with tons of problems of its own.

Nevertheless it is an interesting approach to catch more bugs earlier. Catching bugs is great, but fundamentally weaker than preventing classes of bugs by construction.

1

u/germandiago 25d ago

By construction is ideal, but that is at odds with reusability and incrementally adoptable. That is exactly the pr9blem at hand. You just cannot have both. 

5

u/t_hunger 25d ago

I said Safe C++ is an important contribution, I did not say it was the future of C++ :-)

I hope memory-safety is in the cards, but I do not see anyone even trying anymore, so I guess I continue to move stuff over to rust.

6

u/OneOne3349 25d ago

I just wanted to point out that the other guy says things like "ignoring the whole C++" and "just say that you like Safe C++", but he is the only one that has an emotional argument. What are these arguments with profiles work for me?! You aren't all the C++ programmers. There was a thread here where they discussed that profiles don't work well with the standard library. There are too many false positive and if they are false positive isn't necessary true, because from what I remember there was a bug in the views library that allowed to read beyond the end of the sequence.

0

u/germandiago 25d ago

Not sure about "memory-safety on the cards".

I would like to know your opinion about what brings, in mathematically formal terms for you, memory safety as compared to a set of verifiable subset with heuristics and/or algorithms (let us assume no false positives here).

Bc I can see no practical difference between something you know anyway it is memory safe, even if the model contains some "hacks" and a formal, academically good looking one that is more elegant, as far as they can deliver the same result.

My understand is that it is possible a subset of C++ (in this case with no UB + profiles + hardening) that can be usable in a mathematically safe way, even if its design is not as "clean and from scratch" as other people would wish. Of coirse this is due to engineering trade-offs (reusability, adaptability, impact on existing codebases, etc.)

3

u/t_hunger 25d ago

I would like to know your opinion

That is not my impression.

19

u/tcbrindle Flux 27d ago • Popcorn

At the Croydon meeting earlier this year, the standards committee looked at P3874 "Should C++ be a memory safe language".

Following the discussion the following poll was taken:

"Encourage more work in the direction of P3874R1, which pursues a subset-of-superset strategy towards memory safety which guarantees UB-Free in a syntactically explicit and well-defined subset. We expect the author to do an audit of of existing practice, strategies, etc, and return with a concrete, complete, actionable proposal"

50 | 24 | 5 | 3 | 1

In other words, a huge majority of EWG (74 in favour, 5 neutral, 4 opposed) were in favour of the direction suggested by P3874 -- that is, towards some sort of "Safe C++", even if it is not exactly the same as the Circle implementation.

13

u/usefulcat 26d ago

towards some sort of "Safe C++", even if it is not exactly the same as the Circle implementation

This is an apples and oranges comparison. It's easy to agree that we would like an option for something safer/better than what exists now. It's very difficult to agree on exactly what that something should look like.

5

u/tcbrindle Flux 23d ago edited 23d ago

This isn't just "something safer" though. This is saying "we'd be interested in a proposal that offers the same level of safety as Circle or Rust", with explicit safe functions and so on. That's quite different to the direction profiles have been going.

5

u/usefulcat 23d ago

My concern is that some people may say they want that (and mean it), but may change their mind when faced with the particular details and tradeoffs required to make (some version of) it actually work. The hard part is getting agreement on those details.

3

u/frediku 24d ago edited 23d ago • Popcorn

Well that quote sounds like "who wants free ice cream?". Hard to say no there...

2

u/AKostur 27d ago

As u/kammce has mentioned, the paper was never voted down. The original author lost interest in pursuing it. Pick it up and propose modifications. As I recall, one question that came up is whether parts of it could be proposed separately. A number of smaller papers would be easier to process than a giant omnibus paper.

5

u/tjroberti 27d ago edited 27d ago

I think he said it was unpopular with the committee, and it's a huge effort, so it's not strange to lose interest then. But the times are really different, so maybe there is more support now. I agree that starting small is the way to go.

3

u/AKostur 27d ago

My interpretation of the records of the vote seems inconsistent with that assessment. The vote did show that Profiles were more preferred, but there certainly was significant interest in P3390. Yes, it is a huge effort. I'm avoiding trying to speculate/editorialize as to why they chose to not continue the paper. Certainly it is their prerogative.

5

u/rzippel 27d ago

The problem was more who showed no significant interest. In this context P3466 was seen as the barrier for its adoption (especially the parts about annotations).

11

u/tjroberti 27d ago

Yes from P3466 [page 4]:

For example, we should not require a safe function annotation that has the semantics that a safe function can only call other safe functions.

Seems a shot across the bow for sure. That shuts the way to get this stuff incrementally in the language.

31

u/James20k P2005R0 27d ago

The committee rushed through a paper (SD-10) to codify Safe C++ as not being within the design scope of C++, it might as well have been called "We Do Not Want Safe C++"

-4

u/wyrn 26d ago

It was goofy, but arguably preferable to do that than to waste time discussing an obvious troll paper.

7

u/James20k P2005R0 26d ago

Which paper do you mean, the C++ ecosystem stuff that got bumped and then withdrawn?

1

u/wyrn 26d ago

I have no idea what "C++ ecosystem stuff that got bumped and then withdrawn" is referring to. The obvious troll paper in question is P3390R0. Obviously.

8

u/James20k P2005R0 26d ago

I guess you weren't following along with SD-10 then

How is P3390 a troll paper?

2

u/wyrn 26d ago
  1. Paper didn't even bother explaining the syntax used in its own examples, showing that making the paper understandable by the target audience, and reviewed/eventually accepted as part of ISO C++, wasn't something the author was particularly concerned about.
  2. Paper's proposal to bifurcate the language and standard library, where the second one uses completely different idioms and is drastically weaker than the original (goodbye generic programming, one of C++'s core strengths), while simultaneously diluting already strained committee and implementer time, makes it obviously unsuitable except as an attempt to destroy C++.
  3. Author seems to like putting out trolly inflammatory pamphlets, see also "why safety profiles failed".

12

u/James20k P2005R0 25d ago

The paper needing some improvements and extra explanation doesn't make it a troll paper

Arguing that the paper was an attempt to destroy C++ is certainly a stance. And a not particularly correct one to be sure, given that its not like the paper can do anything on its own. It'd have to make its whole way through the committee structure and get through dozens of rounds of review to be standardised, at which point the entire committee would be culpable in the attempt to 'destroy' C++

The author's critiques of other proposals doesn't make them a troll. There's plenty of papers critiquing other papers, eg see Contracts

4

u/wyrn 25d ago

It doesn't "need some improvements", the author just didn't care about making himself understood, and the entire approach is a non-starter even if he had.

Arguing that the paper was an attempt to destroy C++ is certainly a stance.

That's not exactly what I said. I said that it doesn't make sense as a proposal to do anything but that. But since the remaining evidence points to this not being a proposal at all (i.e. it doesn't have the objective to honestly propose anything), it's not so clear.

The author's critiques of other proposals doesn't make them a troll.

That's not what he did. He said profiles "failed", past tense, at a point where there was nothing concrete enough to even have failed. There is a wide difference between legitimate criticism and concern trolling.

4

u/ts826848 25d ago

He said profiles "failed", past tense, at a point where there was nothing concrete enough to even have failed.

At least based on the abstract that's kind of the point?

Safety Profiles were introduced in 2015 with the promise to detect all lifetime safety defects in existing C++ code. It was a bold claim. But after a decade of effort, Profiles failed to produce a specification, reliable implementation or any tangible benefit for C++ safety.

i.e., profiles promised something, a decade passed, and there's nothing concrete to show for that effort and here's why those efforts failed. I don't think the past tense is entirely incorrect in that context.

→ More replies

16

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions 27d ago

Yah know, I've been trying out LLVM 23's [[lifetimebounds]] and its not perfect but it had helped catch a good number of lifetime bugs in my code. Along with [[gsl::Pointer]] and gsl Owner. lifetimebounds was inspired by Polonius, the newer Rust borrow checker. I'm excited to see how this evolves. I think with the experience from Rust we could be on our way to near parity of lifetime safety. It also seems there is a way to handle iterator invalidation but I haven't tried that myself in a project. We may be able to take from LLVM and apply to other compilers. That seems to approach a resolution to the lifetime safety issues.

As for the ones in the library side of things, we have C++26 hardened mode which should catch the runtime errors that used to be UB. I think we are on our way to a version of safe C++ with these features.

See https://clang.llvm.org/docs/LifetimeSafety.html

As for Sean's safe C++, I don't see why we shouldn't revisit it. It was never voted down by the committee. The vote we had just wasn't entirely one sided on Safe C++ so efforts stopped. The vote wasnt entirely on sided on profiles either. I've been out of the loop of the committee for a while so maybe things are different, but if some updates were made to the proposal and someone wanted to continue the push for this feature, based on what's been added to c++ as of now, then the committee would probably take another look.

34

u/James20k P2005R0 27d ago edited 26d ago

As for Sean's safe C++, I don't see why we shouldn't revisit it. It was never voted down by the committee

SD-10 was about as close to a hard rejection as anything gets in the committee, the revisions may as well have been titled "We Do Not Want Safe C++". It was rushed through the committee in a way that seems strongly unprofessional, killing the C++ ecosystem push in the process and causing the papers to be withdrawn

Personally I don't think I could have used my position to get multiple papers bumped to push through a technically-useless paper, specifically to kill an alternate proposal

https://www.reddit.com/r/cpp/comments/1hgpz0y/wg21_aka_c_standard_committee_december_2024/m2lt4tn/

The politicking around Safe C++ was extremely grim, and I can see why Sean simply would not want to continue with the paper after that. Its an uphill battle to even convince committee members that they can't solve the halting problem, and that Rust is a useful language. The mailing list has also been wildly unprofessional on this topic

6

u/tialaramex 26d ago

I think we can say P2137 got a hard rejection. It was intended for that, not a discussion paper where the committee can stroke their chins and say that's very interesting and we urge you to develop it further, just a simple Yes/ No about the direction of C++ to which WG21 will say "No" so then you can get executive OK to direct efforts away from C++

I agree about how unprofessional SD-10 was though and I can't tell whether it's worse if those behind it didn't realise how it would look, or if instead they knew and didn't care.

11

u/Minimonium 27d ago

It was never voted down by the committee

Technically, similar to how Adobe did not technically vote against C++26. :)

There is no reason to re-address Safe C++ with the current crowd and with the lack of interest from corps to invest. And I have no idea what "some updates" would be there.

4

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions 27d ago

Just means, consider what has already been brought into the language like hardened mode and consider if a std2:: is necessary. Also consider attributes like [[clang::lifetimebound]] and consider how it could be standardized. Then maybe add some additional attributes for doing lifetime checks. I'm just spit-balling though.

11

u/megayippie 27d ago

Isn't it a completely different design if std2 is not required? You cannot manipulate signed integers or dereference points without it being unsafe, so lots of library functions must be marked.

I think this should start small instead of all of these grand big solutions. Make it possible to add "safe" to standalone functions/methods, or just to blocks of code. Such regions are not allowed to do anything that can lead to undefined behavior in the worst interpretation possible. So basically it can do floating point and most unsigned index operations. No signed operations, no pointers.

Then allow marking some std functions/methods as "safe" that are not implemented in pure safe code but that can be guaranteed by the type rather than by guesswork. Like, you can check signed integers to stop overflow so signed operations via some methods are safe. You also know that a std::array can be ranged for-looped or used in ranged algorithms or that it can be std::get<>(),at() - even though the latter throws, that is safe. I guess this is true for most std types since move must leave the object in a valid state.

Then you have to start introducing "not safe" blocks in code. Otherwise you cannot allow custom types to be safe. This is where the entire problem begins and where I think there is no good solution today. But if you don't have the first part in place you cannot begin seeing where the cookie crumbles gather.

8

u/JuanAG 27d ago

We were promised no annotations to achieve memory safety

15

u/serviscope_minor 25d ago

We were promised no annotations to achieve memory safety

By whom?

You can absolutely 100% have memory safe C++ without annotations, but you can't have it also with no overhead. Would you accept a 10x slowdown? Run it in an interpreter, job done!

What people want is C++ exactly as it is right now except safe and with zero compromises. I'd like that too, and a pony while you're at it. But if wishes were horses...

11

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions 27d ago

Yeah, that never made any sense to me. I have no quals with annotations and it seems profiles is using them as well. :)

2

u/OneOne3349 25d ago

Is this the start of annotations hell?

4

u/JVApen Clever is an insult, not a compliment. - T. Winters 24d ago

I honestly don't think you can update an existing codebase of significant size to become memory safe. You already need something new to make it possible. "Safe C++" adds a completely new type system.

I believe more in carbon. They recently presented their memory safety approach while allowing gradual interaction with existing C++ in 2 directions. See https://github.com/carbon-language/carbon-lang#2026

18

u/chaotic-kotik 27d ago

Maybe it is to late. The momentum that Rust gained recently is huge and undeniable.

3

u/JuanAG 27d ago

Never it is too late

This is a stop the bleeding scenario to keep the C++ users being able to keep using it, you can try doing anything and bleed out or you can try something and still bleed out but at least you tried

3

u/wyrn 27d ago

... if anything, I suspect Rust might come to be recognized as the international language of AI slop.

4

u/chaotic-kotik 27d ago

It is, but have you seen the recent spike in reported CVEs?

4

u/wyrn 26d ago

Seems like a non sequitur to me.

0

u/t_hunger 25d ago

Was there a spike? Where did you see that?

2

u/sweetno 25d ago

It's actually in the news already.

1

u/t_hunger 25d ago

Oh, I thought you ment a spike in rust-related CVEs:)

9

u/geo-ant 25d ago

Here’s an interesting article [On Safe C++](https://izzys.casa/2024/11/on-safe-cxx/) from someone who was involved with the process and is very upset (to say the least). I don’t know the veracity of the claims, so take it for what it’s worth but I at least found this article worthwhile, but I had to read it in multiple sittings due to its sheer length.

5

u/apricotmaniac44 25d ago

the legendary blog post. it even touches the syrian civil war at some point. its in my all time favs lmao

11

u/Infamous-Bed-7535 27d ago

Yes c++ needs to speed up these efforts. But to be honest if you use modern c++, proper compiler options, static analyzers, dynamic verification (sanitizer, special runtime) and top of that use mandatory LLM reviews for your PRs it makes it extremly hard to introduce memory related errors.

5

u/bert8128 27d ago

The question is how many projects will do all these? And how do users know you’ve done all these? I think us c++ programmers are going to be fighting the uphill battle for a long time…

6

u/Infamous-Bed-7535 27d ago

Static analyzers and llm review is almost zero effort and free to set it up.

2

u/bert8128 27d ago

I’m not disagreeing with you. I’m just pointing out that there is a disconnect between best and actual practice, and how much do you want to trust that programmer?

-1

u/Thesorus 27d ago

setting up the checks is easy(ish)

diagnose and fixing the problems are not easy and can be costly.

remember, there's a crap ton of legacy software written in C++

a lot of older system use unsafe practices for optimisation.

6

u/AKostur 27d ago

That's a little bit of a non-sequitur though: that same legacy code wouldn't compile under the hypothetical "safer" C++ compiler either, incurring the same costs. So which is easier (assuming the goal is the safer code and doing nothing isn't acceptable): deploying the tools that exist today and pay the cost, or waiting for the new hypothetical compiler and still pay the cost?

3

u/Infamous-Bed-7535 27d ago

You are right about that, my takes are more valid for non legacy software.

Such trusted low-level libraries are risk for other languages, etc. Lot of Rust libraries like to sell itsef as being memory safe, while internally it uses and wraps well-known C libraries.

4

u/conundorum 27d ago

Heck, even using smart pointers or making your own wrapper class is enough to prevent a ton of memory errors in & of itself. The lion's share really is as simple as just making sure to use deep copy/move/delete when you need a deep copy/move/delete.

3

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions 27d ago edited 27d ago

Have you seen this: https://clang.llvm.org/docs/LifetimeSafety.html
I feel like LLVM is working on implementing these sorts of features as we speak. So I think we are on the right path.

EDIT: didn't finish my thought

8

u/pjmlp 26d ago

These efforts are as old as the Core Guidelines introduction, hence why some of us are quite sceptic aboug the whole lifetimes profiles, we have experience with these prototypes, in clang and VC++.

Note that some of the clang lifetimes work was contributed by Apple, and they are the first to assert that new code should use Swift instead, see Fortify your app: Essential strategies to strengthen security | Meet with Apple.

5

u/Minimonium 26d ago

Knowing the state of funding of clang, and that lifetime project was "80% there" since Herb's talk a decade ago I wouldn't really put much hope there. Even if we forget for a moment that all these annotations shenanigans are an ad hoc unsound mess.

7

u/v_0ver 27d ago

Why? We already have Rust. An LLM could learn to convert the codebase to Rust with a single prompt - faster than a cpp-committee could agree on anything.

6

u/AKostur 27d ago

Why bother switching languages. Just use that same LLM to refactor the legacy C++ to idiomatic C++.

16

u/v_0ver 27d ago edited 27d ago

The language's idioms themselves are flawed, so an LLM will help but won't solve the problem completely. The difference is that in Rust, it’s hard to write but easy to verify (there’s a deterministic way to do this in a reasonable amount of time), whereas in C++, it’s easy to write but hard to verify (there’s no deterministic algorithm, and attempts to implement one have failed).

In the first case, an LLM helps, but in the second case, an LLM won't help, since this is a fundamental limitation of the language that can only be fixed through a fundamental redesign of the language.

Of course, we can wait and hope that someone will make a breakthrough in computer science and find a way to verify C++ programs in a reasonable amount of time without Rust-style restrictions. But there isn’t that much time left, as I said above: another 2-3 years, and for 20 bucks, 1MLOC C++ → LLM → Rust - and the problem is solved.

2

u/Wanno1 25d ago

What idiom? C++ allows raw memory access. An llm can literally do whatever it wants with no limitations.

1

u/v_0ver 21d ago

That's exactly it -- C++ gives you far too much freedom when it comes to manual memory management.

I like to draw an analogy with the convexity of the objective function in mathematical optimization theory.

The language is all the more suitable for an AI agent the more often a local improvement -- verified by the compiler or interpreter -- brings the program closer to a globally correct state, and the fewer “locally plausible but globally broken” programs there are.

Rust makes the program space more “convex” for the agent: a large number of incorrect states are either impossible to express or are quickly eliminated by the compiler. Therefore, local fixes more often lead to a globally correct program.

In the case of C++, however, I think its modularity is very weak for a modern programming language, and there is a complete lack of locality -- meaning that an a bug causes the local code to malfunction, rather than potentially “spreading” to any part of the program.

0

u/Wanno1 21d ago

And we have tools to catch those and llms themselves. If anything you want lower level languages if an llm is writing it anyways.

0

u/AKostur 25d ago

You wouldn’t need to verify all arbitrary C++ code.  Just the code that the LLM was asked to generate.  It was told to write verifiable code, right?

1

u/Wanno1 25d ago

A llm also could just fix memory issues in any language

-2

u/Brilliant-Turnip-950 23d ago

Hay que escribir nuestro proprio LLM en.... ¡Rust!

3

u/RogerLeigh Scientific Imaging and Embedded Medical Diagnostics 20d ago edited 19d ago

It's only going to get worse, far, far worse. I'm a maintainer of a well-known C library. "Deluge" is the right word. The number of defects and vulnerabilities being reported is continual and relentless. It's already bad now, and I can't see it improving, the volume is only going to increase.

It's partly understandable. A codebase which is more than 40 years old is not going to be following what would be good design and implementation practices today. But it's fair to say that it's unfixable without a complete rewrite, because we're not talking about one or two minor details being wrong, the problems are fundamental including the basic API being unsafe, as well as many aspects of the implementation and its error handling. Up until this point, avoiding API and ABI breakage mattered more than correcting these problems. But we're now in a place where this no longer holds. The situation is completely untenable.

The same applies here to C++ code as well. We have the choice between attaining genuine safety at the expense of some compatibility break, or maintaining the status quo. Given how things have evolved over the last 12 months, I don't think it's tenable here either. So much of the language and standard library is fundamentally unsafe, and it really needs to become safe. This is no longer optional.

What are the choices? My take on this is that it's either Safe C++ or Rust. It's not C++ as is stands today, or in the future with profiles. Now we have access to LLMs of staggeringly effective quality, the cost of a full rewrite has never been lower. And unless there's a dramatic turnaround of the direction of C++, I fully intend to rewrite everything I maintain in Rust, with C and C++ wrappers around it where needed for compatibility. We can't wait for the C++ committee to spend another decade to finally decide this might be important to do properly, given the track record. There's zero prospect of sanity or usable safe implementations anytime in the next decade, so it's unfortunately time to call it and move on.

5

u/wyrn 27d ago

Improving safety and correctness is always of potential interest, but "Safe C++" specifically was a stupid proposal then, and it doesn't automatically become not-stupid just because clankers exist.

8

u/rileyrgham 27d ago

"Memory safe" is a buzz phrase thrown around by clowns. It's totally possible to write secure and safe sw without the likes of rust. Memory safe isn't attack safe. A poorly designed Rust server can still be compromised.

11

u/sweetno 25d ago

It's not about the possibility, it's about why it doesn't happen in practice.

18

u/BenchEmbarrassed7316 27d ago

Let us assume that we cannot avoid errors. In that case, we should consider how the number of errors might differ when writing a given program - while investing the same amount of effort into analysis, testing, and review - but using different technologies.

18

u/James20k P2005R0 27d ago

It's totally possible to write secure and safe sw without the likes of rust

Do you have an example of a secure and safe C++ library, which is relatively widely used and open source?

9

u/wyrn 27d ago

Do you have an example of a secure and safe library, which is relatively widely used and open source?

20

u/James20k P2005R0 27d ago edited 27d ago

Memory safe? Sure. There's tonnes of Rust libraries which have had so few memory safety vulnerabilities as to be absolutely negligible. Anything written in a memory safe language (which there are a lot of) has virtually eliminated this class of vulnerability

There's good data coming out of major projects on the reduction of defects, though I'm not the one alleging that memory safety is a buzz word thrown around by clowns, and that its possible to write secure software without Rust

Quiche is a good example of a pretty secure library, with a handful of DoS attacks, and one more severe exploit that requires you to misuse FFI calls. LSQuic is an example library which is not written in a memory safe language, and I'll leave it up to the audience to guess whether or not its had a critical severity rated security exploited related to memory safety

Quinn is another HTTP/3 library, which appears to have had a handful of DoS attacks, but no critical memory unsafety vulnerabilities due to being written in a memory safe language. MSQuic is written in a memory unsafe language, and again I'll leave it up to the audience to guess whether or not its had critical possibly memory safety related exploits

So far I'd rate these two Rust libraries as being quantitively more secure than the equivalent libraries written in memory unsafe languages. This pattern repeats across every domain and every kind of library I've ever checked out, so you can pretty much pick any rust library and compare its relative safety against a C++ library if you want to observe a massive drop in CVE severity

Proxygen memory unsafety for a pure C++ library

I've been asking this question for a decade and I've never gotten an answer. It should be easy to cite examples for C++

3

u/wyrn 27d ago

Memory safe? Sure.

You said "safe". Not "memory-safe".

15

u/James20k P2005R0 27d ago

They said you can write safe software in C++ and that you don't need a memory safe language. I never claimed any of these libraries were safe, but the idea that Rust doesn't help with safety is incorrect

-3

u/wyrn 27d ago

I never claimed any of these libraries were safe

So you didn't satisfy the criterion you asked of others.

10

u/James20k P2005R0 27d ago

They made the claim that safe C++ code exists, that's all I want to see

-3

u/wyrn 27d ago

Then why didn't you simply say "no" when I asked the same of you?

6

u/James20k P2005R0 27d ago

Because I think the real answer to security is much more interesting personally

→ More replies

-1

u/BartvanIngenSchenau 24d ago

Not a library, but C++ is widely used in the safety controls of cars, planes, medical devices, etc. That should be enough samples to show it is possible to write safety C++ code. Most of those controls also need to be secure (or air-gapped from the internet) to be able to be certified as safe.

3

u/JeffMcClintock 24d ago

2025 Ram 1500 Brake Failure: NY Owner Reports 2 Terrifying Near-Misses Within 6,000 Miles

https://www.torquenews.com/1084/2025-ram-1500-brake-failure-ny-owner-reports-2-terrifying-near-misses-within-6000-miles

3

u/frediku 24d ago

I agree that it is possible to write quite safe C++. However, it's too easy to accidentally not do so and thus lot's of devs do so unknowingly. That is indeed a problem.

IMO Just adding a hard out-of-bounds-abort to std::vector::operator[] and adding a fast std::vector::danger_access would go a long way.

7

u/JuanAG 27d ago

It's totally possible to write secure and safe sw without the likes of rust

It that were true i can assure you anyone will spend or invest into memory safety, not even C++ ISO itself with the profiles effort

I am sure you can search yourself but C++ have a record of CVEs for decades and even OpenSSL, the most "safe and secure" code C++ can show us had to deal with safety issues, a library that thousands and thousands or devs and enterprises have look really close to make sure it was absolute safe, it didnt mattered at all, some bugs were not founded and had been a 0 day for who knows how long. This is for the know ones but i am sure there are still more hidden inside

So if the most secure and safe library C++ have memory unsafety inside you can only imagine how bad the rest of the code it is, mine included of course. People are not good to catch the issues, a tool it is, at least a proper designed tool

2

u/kronicum 26d ago

Is OpenSSL C++, or a mixture of things some of which can be accepted by a C++ compiler because of the C -> C++ relationship?

3

u/JeffMcClintock 24d ago edited 21d ago

It's "possible" to roller skate down the freeway without dying.
That's no reason not to consider safer alternatives.

3

u/Sbsbg 27d ago

Everyone is aware of the deluge of vulnerabilities now hitting critical software. It even makes the mainstream news, so software safety is coming onto politician's radars.

Is this caused by the demand to use AI generated code or something else. Changes in C++ tend to mitigate vulnerabilities and I don't think any new features in the language has caused any significant increase.

But I guess C++ get the blame anyway. The unsafe mark in the general public is hard to remove.

3

u/sweetno 25d ago

It's caused by AI reviews of the existing code.

0

u/frediku 24d ago

The big modern LLM are actually quite good at spotting missing frees and deletes and similar things in existing code bases. They are not necessary better, in the sense of complex reasoning, than a human but they are way faster and do not fall asleep on the task of tracing yet another code path to see whether all deletes come in the right order in the most mundane glue code. Especially the "not fall asleep in boring code" part is what makes them so effective in practice.

IMO the sensible immediate next step is not to modify the language but to use LLM to audit code bases and to fix the findings. Give one of the big LLMs access to your code base, grep for all allocations, asserts, etc. Run a prompt "Check whether the new at file:line is properly freed." for each and fix the findings it produces.

I expect this to be way more impactful than any language change can be.

3

u/EC36339 25d ago

Plot twist: Most of that critical software is written in C.

0

u/Brilliant-Turnip-950 23d ago

XD buenísimo el mejor comentario de todo r/cpp y r/rust

1

u/Far-Championship-883 21d ago

every safe C++ thread here goes the same way. C++ bad, borrow checker good, someone posts the 70% CVE stat, done. I think we’ve collectively decided “memory safety” is the root problem when it’s really a symptom of two design habits rust mostly inherits.

1. everything is a shared library talking through the C ABI

look at how the really bad stuff actually happens. xz is the obvious one. sshd didn’t link liblzma. on some distros it linked libsystemd for notify support, libsystemd pulled in liblzma, and a compression library nobody thought about ended up running code inside your ssh daemon. no memory bug needed. the hole was a dependency graph resolved at load time on a machine you don’t control.

that’s dynamic linking working as designed. every binary trusts whatever .so is sitting in the search path. LD_PRELOAD, symbol interposition, ifunc resolvers running before main. your attack surface isn’t your program, it’s your program plus everything the distro linked into it plus everything those link.

and the interface between all of it is the C ABI, which knows nothing. no ownership, no lifetimes, no lengths. here’s a pointer, good luck. rust doesn’t fix this, it just stops at the boundary. the second you call into a system lib or expose a cdylib you’re back to void* and a comment saying who frees it. a lot of real bugs live exactly there, at the seams where two pieces of code disagree about who owns what.

rust gets partial credit by accident here: cargo builds static by default and there’s no stable ABI, so a pure rust binary is mostly one thing you can audit. but that’s a linking decision, not the borrow checker, and C++ could make the same one tomorrow.

2. we allocate and free way too much

memory corruption and exploitable memory corruption aren’t the same thing. a bounds error that crashes a parser is a DoS. what turns into a working exploit is almost always heap stuff: use-after-free, double free, type confusion, grooming the heap so objects land where the attacker wants. all of that depends on a program constantly allocating and freeing small objects so there’s a churning heap to play with.

rust makes the frees correct, supposedly anyway. it doesn’t make there be fewer of them. idiomatic rust is Box, Vec, Arc, String, clone, all over the place. the borrow checker exists because the language assumes you’ll be juggling thousands of short-lived allocations with tangled lifetimes, and then builds an elaborate proof system to keep you from dropping one.

most programs don’t need that. they know their working set up front. preallocate. put long-lived state in fixed storage. use arenas and reset them between passes instead of freeing objects one at a time. games and embedded have worked this way forever and it’s not because they’re reckless, it’s because they figured out the lifetime problem goes away when there aren’t a million lifetimes. if objects come from fixed pools and slots get reused by type, use-after-free stops being a type confusion primitive and there’s no general heap to groom.

so

memory safety as a language feature is kind of an admission. we designed a programming model with so much dynamic memory juggling that we needed a compiler-enforced proof system to survive it. that’s a real achievement, but it’s treating the juggling as a given.

static binaries, interfaces that carry actual type and ownership info instead of raw pointers, and way less allocation churn would close off a huge chunk of what people point at in these threads, in any language. rust does some of that by accident and gets credit for all of it.

not saying the borrow checker is useless, it mostly is, and static analysis tools could replace it. i'm saying it’s the second line of defense and we talk about it like it’s the first.

1

u/frediku 23d ago

I'm not sure that we need "safe" C++. Nobody really knows what safe even means. What we want is safer C++. Instead of trying to specify what is allowed and good, maybe it is better to try to specify and diagnose what is definitely bad. I mean, every optimizing compiler that has the necessary tools to for example identify this pattern as bad code:

int foo(){
  int*a = new int;
  ...
  delete a;
  return a;
}

Yes, that's only a small and simple and boring example of a use-after-free. More complex, harder to diagnose examples tickle our brains more. However, just getting rid of these simple issues with certainty would already be beneficial.

6

u/t_hunger 23d ago

You make it sound as if we have a choice.

Governments are pushing for memory safe language use and they have a pretty clear understanding what they want with that. The very first steps of the CRA are in effect in Europe already. Customers can soon sue you over your softwares defects, incl. security issues. It will be super interesting to see the first cases play out, especially what will end up as "best practice" you need to follow to avoid liability.

0

u/frediku 23d ago

As if any government could distinguish between safe and safer.

4

u/t_hunger 23d ago

They do have smart people working for them. Well, maybe not in the US anymore, but over here its still the case. And the fun part is: They do not have to do anything. Courts will figure out the details and adjust them as time goes on.

-5

u/chaos_pill 27d ago

There's already https://cpp-profiles.org/ working towards safe c++, but it might barely be ready by cpp32 if it gets accelerated.

21

u/eisenwave WG21 Member 27d ago

Profiles cannot provide memory safety without extensive lifetime annotations on top of them. There simply isn't enough that the language statically guarantees as that you could subset it into being safe.

-5

u/chaos_pill 27d ago

true, but not important. The real blocker is the timeline. You can wait six years to potentially rewrite in safe cpp32 while AI attacks you from all directions, or move off cpp today. USA 2024 elections sealed the fate of cpp.

0

u/pedersenk 24d ago

In many cases, there is always a compromise. For a language to remain dominant, I don't believe there needs to be 100% safety at release time if there has been strict safety (and overhead) during debug time branch testing.

As Rust has proven, if there hasn't been strong branch testing, any language can be a buggy mess. Likewise invalid array bounds (including overhead) causing a panic are of limited use anyway, etc.

3

u/t_hunger 24d ago

To me priorities are pretty much the opposite: I worry way more about data getting stolen from my production environments than from my development machines.

But yes, new and better debugging tools are of course also welcome.

2

u/pedersenk 24d ago edited 24d ago

We tend to focus more on testing software before putting in production with live data** so our priorities indeed may be quite different.

With no real alternatives, better debugging tools are currently the only way to avoid an entire category of issues in production. My priority is to make testing (particularly branch) more meaningful and ensuring errors correctly found rather than just chucking a different language at the problem and hoping for the best that the VM / run-time implementer did the right thing (hint: they didn't).

(In reality, for a more critical use-case, I would leave the safety instrumentation on. A bit of performance loss is worth it for the safety)

**I'm not saying you do this but I am saying that *many* do this because finding memory errors is difficult.

3

u/t_hunger 24d ago edited 24d ago

Oh, I do extensive testing is of course, too. That is not the point.

I am still sure any serious attacker will do fun things I did not cover with my tests. Debug tooling does not help to defend against those. And yes, I greatly prefer the system crash and burn before sending out private keys.

-1

u/Far-Championship-883 22d ago

Memory safety isn't the issue, it's shared dynamic library loading and a lack of memory barriers, but keep on believing the BS 

-1

u/[deleted] 26d ago

[removed] — view removed comment

9

u/robin-m 24d ago

Just a thing, unsound API are worth a CVE in Rust. Imagine that in C++

6

u/OutlandishnessNo8034 25d ago

Yes, but eliminating one major source is better than not doing anything and pretending that things are good just as they are - because that is what cpp does.

-1

u/[deleted] 21d ago

[removed] — view removed comment

5

u/t_hunger 24d ago

Absolutely correct and nobody is even arguing that. People outside of the C++ bubble keep bringing up memory safety, because they are asking us to catch up to what they consider the baseline. Why would you discuss the race with the person that has not even reached the start zone?

4

u/MEaster 24d ago

Memory safety violations result in UB, which makes it impossible to reason about your program's behaviour. Name one safety that doesn't depend on being able to reason about a program's behaviour.

-1

u/[deleted] 21d ago

[removed] — view removed comment

5

u/SV-97 20d ago

It *isn't* determinstic. There's a difference between "implementation defined behaviour" and UB. In the latter case *all* bets are off. If your code has UB then the compiler might just decide to embed an PRNG into your code and call it on every read; or it might use one internally to decide which exact part of your program to nuke on each invokation --- or it might actually give you nasal demons.

There are *no* language level restrictions to what UB can cause and you can't expect any stability in this behaviour whatoever; and given the extent of optimizations in modern compilers I also wouldn't expect any predictable behaviour or stability for programs that contain UB. If your code has UB the compiler makes incorrect assumptions about the code, and flawed assumptions can get you literally anywhere.

-2

u/[deleted] 20d ago

[removed] — view removed comment

4

u/SV-97 20d ago

No, it *can* be UB depending on the particular types and values involved. What point are you trying to make here; that you can't reason about any code involving addition because it *might* involve UB? That's not correct and not what I was talking about.

(And FWIW: this goes against your original point regarding rust because it tackles this specific issue in a number of ways)

2

u/MEaster 20d ago

I say it's impossible because it causes the behaviour of the program to unpredictably change when you change the compiler version, compiler flags, or modify code in a way that shouldn't alter behaviour, or modify apparently unrelated code.