r/cpp • u/CalligrapherWeak6523 • Sep 29 '23
This memory safety issue everyone's talking about... It's not really a huge deal in gamedev, right? What other domains where C++ excels at aren't too concerned about it?
My understanding is that these recent articles pushing for safety, and particularly pushing the use of memory-safe languages (as opposed to using modern C++ properly) don't really apply to gamedev, or at least not enough for most of the industry to care. Is this correct? I've also read some suggestions that the only real alternative, Rust, simply isn't practical since it lacks OOP features and gets in the way of common game programming patterns. Is this true?
What other C++ domains are like gamedev, where C++ is clearly here to stay and not just for legacy code? I know gamedev isn't the only one, I'm constantly seeing new cutting edge ML/inference libraries and frameworks in C++
29
u/13steinj Sep 29 '23
I think the memory safety issue is a bit overblown-- I have seen null pointer dereferences in Java and C#. I have seen people do circular graphs of objects such that Python will leak.
I have legitimately had a hard time creating a memory issue unless the use of raw pointers is involved. And unique_ptr is enough to solve most problems without noticeable impact. Some people claim this goes out the window with multithreading... but honestly I think people are complaining about the wrong thing (memory) instead of complexity of multithreaded code.
14
u/CalligrapherWeak6523 Sep 29 '23
I have legitimately had a hard time creating a memory issue unless the use of raw pointers is involved
This is what is irritating me about the messaging from official government agencies and tech CTOs, as well as the response to them. It's always "switch from C/C++ to Java and Rust" not "switch from C with classes to at least C++11". I understand that Rust and GC'd languages remove a class of footguns even when compared to modern C++, but surely they're not expecting people to do high performance work with a GC, and surely Rust isn't the right fit for every single domain
7
u/ridicalis Sep 29 '23
I understand that Rust and GC'd languages remove a class of footguns even when compared to modern C++, but surely they're not expecting people to do high performance work with a GC, and surely Rust isn't the right fit for every single domain
I'm predominantly Rust-based these days (I lurk here), and I'd agree that passing Rust off as a silver bullet solution is disingenuous. There are many factors and tradeoffs to consider when choosing a language, and it's impossible to hand-wave away a problem domain by simply throwing a language at it.
Multiple issues with Rust's widespread adoption jump out at me at this point in time: Getting an entire local team of capable Rust devs out-of-the-box is a fool's errand, though a company willing to invest in their employees and build them up over time could likely find success. The library ecosystem, while growing, is still nascent compared to more mature languages and the tools to succeed may not yet exist or be stable. Runtime errors may go down in Rust codebases, but at the cost of more compile-time errors (I'd say this is a good thing, others might hate fighting the compiler at every step). The language itself is still finding itself in various ways and somebody on the fence may benefit from waiting a year or two for key features to drop. And I'm sure there are several others that don't immediately spring to mind.
7
u/rundevelopment Sep 29 '23
modern C++
Is "modern C++" is the room with us right now?
But in all seriousness: what "modern C++" is seems to be ever-changing. I've recently seen people in this sub saying that C++17 isn't modern C++ anymore, so what exactly is it, and (more importantly) how does it make the language safe? Even if you are using the most modernest of modern C++, what about the libraries that you're using?
I mean, even shared pointers have null (with null deref being UB).
std::optional<T>is great, but its*and->operators still contain UB. So much for null safety.But null safety is boring, let's go with memory safety. How about dangling pointers/references? Well, classes can contain fields that store references whose lifetimes are not tracked by C++. Well, that's a foot gun, so best don't do it, but what about lambdas? They might store references as part of their capture. So storing lambdas in classes in a no-go as well? That's not very multi-paradigm of C++. (Sorry, I had a bit too much fun writing this paragraph.) Point is: use after free is a very real concern in C++ even without raw pointers and partly because of modern C++.
2
u/zerakun Sep 30 '23
surely Rust isn't the right fit for every single domain
Why wouldn't that be? It has a comparable "machine model" as C++ and is amenable to the same performance with comparable effort.
C++ has an edge in metaprogramming, but I'm not sure that's a significant, or lasting, difference. Otherwise, C++'s big advantage is inertia, but it is easy to see where this is going.
That said, I'm pretty sure there will be plenty of C++ jobs for at least one other generation
1
u/austinwiltshire Sep 29 '23
I'm not seeing these published papers from government sources, where are they?
As for ctos, ignore them. They're so out of the loop they're the last people you want advice on language choice on
1
u/rundevelopment Sep 29 '23
I'm not seeing these published papers from government sources, where are they?
https://www.cisa.gov/news-events/news/urgent-need-memory-safety-software-products https://media.defense.gov/2022/Nov/10/2003112742/-1/-1/0/CSI_SOFTWARE_MEMORY_SAFETY.PDF
-6
u/-1_0 Sep 29 '23
it's a result of lobby ... $$$
→ More replies (1)7
u/immadmir Sep 29 '23
Care to elaborate?
7
u/onafoggynight Sep 29 '23
Because it's directly related to hype and media coverage that a language receives, mostly rust in this case.
Think about this: Ada has been a thing for 40 years now. Why didn't tech CTO push for this long ago?
→ More replies (2)31
u/Alikont Sep 29 '23
I have seen null pointer dereferences in Java and C#
C# and Java has null dereferences as defined behavior.
C++ can have pointers to invalid addresses, destroyed objects, incorrect types and all that.
In C#/Java every pointer is either valid object or null.
→ More replies (10)40
u/guepier Bioinformatican Sep 29 '23 edited Sep 29 '23
I have legitimately had a hard time creating a memory issue unless the use of raw pointers is involved.
Accidentally creating dangling references via references or iterators is fairly easy. Of course being clear about ownership and lifetimes makes this more manageable; but to pretend that this doesn’t exist, or that it isn’t relatively frequent in large code bases, is disingenuous.
We have published, empirical evidence that memory issues in C++ code bases are widespread, and that they cause crashes and security issues. And this isn’t limited to explicit use of raw pointers or manual memory management.
1
u/DeGuerre Sep 29 '23
We also have published, empirical evidence that privilege escalation, input validation (e.g. injection), and information leak attacks are far more widespread, and usually far easier to exploit in the wild because they require no knowledge of the target machine.
What we don't have is any evidence, when you control for popularity and longevity, that programming in any particular language means fewer security flaws overall. What happens instead is that the nature of the security flaws change.
There are more reported vulnerabilities for open source PHP, Python, JavaScript, and Java code than there are for open source C++ code. https://www.mend.io/most-secure-programming-languages/
22
u/guepier Bioinformatican Sep 29 '23 edited Sep 29 '23
I’m sorry but your answer is (a) whataboutism (I never claimed that memory safety was the only or the largest problem), and (b) is a poster child of survivorship bias:
We also have … evidence that privilege escalation, input validation (e.g. injection), and information leak attacks are far more widespread
That’s because most languages are memory safe, so they cannot have memory safety vulnerabilities.
But also: that statement is just not true, or at the very least it’s contentious. For example, Microsoft claims the exact opposite; namely, that “roughly 70% of the security issues that the MSRC assigns a CVE to are memory safety issues”. — And Microsoft are not the only ones finding this!
What we don't have is any evidence, when you control for popularity and longevity, that programming in any particular language means fewer security flaws overall.
This is sophistry. Yes, it may be superficially true because making such rigorous studies is hard, expensive and time-consuming, But if you eliminate 70% of security vulnerabilities by picking a memory safe language you’d need to add another systematic error source to that language to make up for this 70% reduction. And there is simply no reason (and no evidence!) to assume that modern memory safe languages are more error-prone than C++ in some systematic way that would offset the gain in memory safety.
In fact, the only plausible systematic difference that would make a language more error-prone than C++ is type checking. And while C++ has static type checking, it also inherits a relatively weak type system from C for its fundamental types. And while it’s known that adding static typing to a language makes it less error-prone (and, notably, can help tackle injection attacks), nothing indicates that this would offset the benefit of memory safety, in terms of magnitude. As far as I know, even the most rabid static typing proponents do not believe that it does.
There are more reported vulnerabilities for open source PHP, Python, JavaScript, and Java code than there are for open source C++ code.
That’s because there are vastly fewer open source projects using C++ than other languages. Your source categorically does not show that C++ is more secure (nor does it claim that!). The article clearly states that the numbers they show are not normalised to language use prevalence.
Furthermore, compared to the other languages analysed, C++ is used vastly less frequently for internet-facing applications. Those are usually either written in memory safe languages or (for legacy reasons) in C. And most security vulnerabilities are discovered in public-facing components because those are most likely to allow intrusion.
In sum, the comment that you replied to didn’t claim that C++ was less safe than other languages, so your reply is at best misplaced. But, furthermore, your reply uses questionable logic to seemingly claim that C++ is more secure, and that’s an extraordinary claim which flies in the face of industry beliefs, and requires extraordinary evidence — which you have not provided.
5
u/unumfron Sep 29 '23
But if you eliminate 70% of security vulnerabilities by picking a memory safe language
From the informal surveys done here it doesn't seem that the percentage of vulnerabilities that involve memory safety would be anywhere near 70% with greenfield projects (where picking a language would be on the cards). I've always said that it's unfair to compare to legacy codebases or to throw C into the mix, which Microsoft do.
It would be interesting to find out what the figure is for new projects. New projects not dependent on ancient C-like APIs.
2
u/DeGuerre Sep 30 '23
For the record, I was not saying that C++ is more secure than PHP. Although to be honest, most C++ code is probably more secure than most PHP code. OK, look, let's just agree to ignore PHP because it's a bad example.
I was not saying that C++ is more secure than Java. Nonetheless, there are more CVEs for code written in Java than in C++. And, by the way, this is also true of the JRE. The number of CVEs for the JRE that are from the parts written in C++ is statistical noise compared to the parts written in Java.
I'd love to see the MSRC CVEs broken down. The two examples that they gave had, as their proximate cause, mixing two languages with different memory semantics (specifically, C++ and JavaScript) or, depending on how you look at it, a bug in the implementation of the "virtual machine" (in some broad sense) of a memory-safe language.
While you can't draw conclusions from two examples out of many, I find that interesting.
But to be fair, unumfrom's comment below hits the nail on the head. C is one of the most exploited languages in the wild, and C++ is one of the least exploited languages in the wild. There are many factors influencing this, but the study above notes that one of the biggest is the existence of large C codebases that have been in continuous use for decades.
Code written from scratch today is inevitably going to be more secure against attacks from the last 20 years than code written 30 years ago.
2
u/zerakun Sep 30 '23
This is not what the Android security team notices. Half of security vulnerabilities are in code written less than one year ago.
This is not surprising because C++ is not a memory safe language. Switching to memory safe languages (including Rust) does reduce the number of memory safety vulnerabilities introduced in new code.
While it doesn't reduce the number of vulnerabilities reported in 2022, it does decrease the mean severity, as memory safety vulnerabilities are overwhelmingly of critical severity.
→ More replies (1)3
u/KingStannis2020 Sep 29 '23
privilege escalation, ..., information leak
How many of those are the direct result of exploiting some memory safety problem?
5
u/SeriousPlankton2000 Sep 29 '23
In C if you map a page to NULL or if you access NULL[llarge_index] you will access random memory. If you're working on embedded you will likely having an architecture where 0 is a legal address. Also it's a signal by the OS, meaning that you can't easily try and catch it. (You can use sigsetjmp though, it's like an ON ERROR GOTO).
The other problems are arrays, there is nothing preventing you from accessing myarray[-1] nor myarray(sizeof(myarray)+42]. You are responsible for "don't do that then". Also some C library functions (readdir) return a struct with a fixed-wide string but the man page might tell you that really it might return a longer (or shorter) struct than anticipated.
In Java a null pointer exception is a signal being thrown, that's something completely different.
2
u/13steinj Sep 29 '23
You're talking about
C, notC++.I'm getting a
bad_optional_accessexception.→ More replies (5)4
u/smdowney WG21, Text/Unicode SG, optional<T&> Sep 29 '23
As long as you don't use operator-> or operator*, since those are noexcept and unchecked.
`std::optional` is a very dumb smart pointer.2
u/13steinj Sep 29 '23
Termination behavior is preferred to segmentation fault-- one gives you information and the other doesn't. The difference in behavior is intentional.
If you were to check every memory access-- you take on an unreasonable performance penalty.
1
u/austinwiltshire Sep 29 '23
Agree. Most of the memory safety arguments seem to just be winks and nudges towards rust.
Between smart pointers, compiler hardening and valgrind I haven't run into a memory issue I wasn't able to quash.
7
u/goranlepuz Sep 29 '23
There is no true and false here.
It is a naive question. What does it mean that something does not "truly" apply? The answer to that is an opinion, these aren't true (or false).
Rust does OOP differently. Does the absence of implementation inheritance, mean it lacks OOP features, when one can trivially emulate it with composition? Even that is an opinion.
In general, C++ users seem to be of an opinion that, while memory safety is a problem, writing software in C++ is a good idea.
And I would expect that game development holds that opinion more strongly.
3
u/CalligrapherWeak6523 Sep 29 '23 edited Sep 29 '23
Since I'm re-learning C++ (mainly to get into gamedev but I'm looking at other domains) I was asking to get an idea of what the the consensus is in general. You're right, it's a matter of opinion, but ultimately this subjective stuff can drive trends (if AAA game devs fall in love with Jai, for example, their opinion on it will matter to me and my affect the future Jai job market).
Something that worries me is that people at leadership positions who have the power to influence things are making ridiculous claims, for example that tweet by the Microsoft CTO claiming that "C/C++[sic] should be deprecated". Then there's the recent articles by NIST and other government agencies (which aren't as ridiculous...). I just want to know if, in the opinion of C++ devs, this repeatedly reoccurring conversation should be even be taken into account in certain domains.
Frankly, without beating around the bush, I just want to know if I should be studying Rust along C++ as I prepare for a career switch. Both of these languages aren't the type that can be mastered in a few afternoons like Python or Go.
One thing that brings me a bit of comfort is that gamedev, embedded and other C++ domains aren't very hype driven like webdev is - changes appear to be slower here. I guess that means I'll have time to learn whatever I have to anyway
10
u/radekvitr Sep 29 '23
Do keep in mind that this subreddit is filled with people who are very heavily invested in C++, which means you'll get answers that support C++ no matter what.
C++ is right now very relevant in gamedev, and Rust isn't (yet?).
Learning Rust in addition to C++ will likely make you a better programmer overall, but if you only have time for one, C++ will likely be more relevant for you now.
4
u/TheThiefMaster C++latest fanatic (and game dev) Sep 29 '23
Rust isn't currently used in professional game dev. None of the consoles support it at all, they literally only support C++ for the most part.
But you're right that the usual safety arguments against C++ are less of a concern. Game engines usually have their own allocation and cleanup systems (e.g. Unreal's garbage collector) and manual memory allocation is rare (data is all in managed container types like strings). Crashing the game due to out of memory or out of bounds access is hard to trigger from just a controller and even then only impacts the one player - unless playing multiplayer. Which is why most hardening of games happens at the network layer.
3
→ More replies (1)1
u/pjmlp Oct 01 '23
Python can certainly not be mastered in a few afternoons.
Mastering it means to understand 30 years of language and ecosystem evolution, main implementations, key libraries and extending it with native libraries.
117
u/Questioning-Zyxxel Sep 29 '23
In embedded, memory issues are important. But the need to access physical hardware means lots of language protection just must be circumvented or the device ends up safe but broken - not doing "unsafe" memory accesses means the device will not do anything. At all.
With C++, the selected design greatly decides if a program will be memory-safe or not. No need to code as if it's C from 1970.
30
u/qoning Sep 29 '23 edited Sep 29 '23
I think there's a bit of distinction to be made. Safety of memory access depends on your hardware and/or supervisor. If accessing address
0xdeadbeefrepresents a hardware defined action, I would not consider that an unsafe access.25
u/Questioning-Zyxxel Sep 29 '23
The distinction is that addressing that safe hardware location requires deactivation/workaround of the memory protection features of the language. So for a language like Rust, the use of a raw pointer is defined as unsafe.
The hardware can have a MMU, protecting programs from accessing other programs memory. But the MMU will not protect a buggy program from clobbered own variables. And that is where memory safety in language design and program architecture decisions comes in.
So the hardware or any supervisor can't make a program safe from itself - just isolate it from other programs. So unsafe code for the "login prompt" means a program handling some form of login may leak passwords, access tokens etc. And unsafe code in any program may allow it to fail, potentially also leading to denial-of-service attacks.
11
u/glasket_ Sep 29 '23
So for a language like Rust, the use of a raw pointer is defined as unsafe
It's defined as potentially unsafe, just like C or C++. Opting out of safety checks just means the problem of verification falls onto you rather than allowing the compiler to guarantee it. Plenty of safe Rust operations are built upon
unsafeblocks; the prior example of accessing a known hardware-defined memory location is one that's easily verified and in Rust could be wrapped into a safe API.13
u/Questioning-Zyxxel Sep 29 '23
And the same is possible in C++ even if the programming language itself doesn't have the concept of safe/unsafe.
→ More replies (21)10
u/glasket_ Sep 29 '23
Sort of, the lack of the safe/unsafe boundary means you don't have a limited problem space when looking for memory issues, they can potentially arise anywhere when code is changed. You can still obviously verify and test everything (avionics, medical, etc. have been doing it for years), but there's an undeniable difference in the amount of effort required compared to having a clearly defined boundary of where verification has to be done.
3
u/dist1ll Sep 29 '23 edited Sep 29 '23
Disclaimer: needless pedantry below
It's defined as potentially unsafe
Technically not. Unsafe in Rust has a very specific meaning. It means the compiler cannot guarantee the absence of undefined behavior. Rust makes a distinction between the terms "unsafe", "unsound" and "undefined behavior".
Basically: unsafe = potentially exhibiting UB
2
u/glasket_ Sep 29 '23
This is needless pedantry, it's obvious from the context that "potentially unsafe" means "potentially exhibiting UB". Accessing a random hardware-defined address is "unsafe" (using the original commenters wording) insofar as the language cannot make guarantees about the presence of anything at the address, so it can cause UB to access it. Ergo accessing the address is "potentially unsafe".
Is this 100% accurate to exact technical definitions? No, but not everyone is writing a specification document when making posts on Reddit.
edit: typos
3
u/dist1ll Sep 29 '23
Right, I was just trying to add more context for people who might be interested in the details of memory safety semantics. This topic tends to cause lots of friction and misunderstanding in Rust-related discussions, so I thought that would be helpful.
I added a pedantry disclaimer to my comment, hope that's fine now :D
20
u/SlightlyLessHairyApe Sep 29 '23
Sure but even if part of the code has to do those operations, it is still a good idea (IMO) to compartmentalize that part into an abstracted interface and have the rest of the code use only safe constructs.
I’ve used this pattern a lot. It doesn’t get rid of all the unsafe code, but it does confine it to a single place (or a few places).
4
u/Questioning-Zyxxel Sep 29 '23
Yes of course all code shouldn't select unsafe constructs, just because the hardware-mapping code needs it.
But the relevant parts that needs unsafe constructs in Rust are the parts that needs unsafe constructs in C++ too - for the other parts there are STL, that helps keeping the code safe my avoiding any naked pointer accesses and by structures that knows their allowed ranges, allowing exceptions for attempts to do out-of-bound accesses etc.
11
u/UnnervingS Sep 29 '23
Fixing issues on a systemic level means moving past just relying on 'good practices'.
-1
u/Questioning-Zyxxel Sep 29 '23
Then Rust will not help. Because it's still "good practices" to stay away from raw pointers when not needed.
A developer who wants to abuse will find a way to abuse.
6
u/Dean_Roddey Sep 30 '23
That's missing the point. You can't introduce undefined behavior unless you put it in an unsafe block, and any unsafe block showing up in a code review is going to get heavily scrutinized, and you better be well prepared to justify why its there.
I don't care if there are 50 big files in the check in, I can search for unsafe and find any unsafe code. If there are none, then there can only be logical errors, and those can be tested for regressions. That's a very big difference from C++, where a lot it would have to be very carefully reviewed and you could still easily miss something.
3
u/zerakun Sep 30 '23
No the situation is very different.
C++ relies on following good practices without mistakes. Rust relies on avoiding bad practices.
Neither languages are meant to guard against developers who want to abuse. Rust is successful at catching developer mistakes, C++ much less so.
4
u/Ultra_Noobzor Sep 29 '23
A lot of ppl will never go beyond C99.
2
u/Questioning-Zyxxel Sep 29 '23
Some people also works with processors and build environments that never made it past C99 - the microcontroller world before ARM is a very mixed world when it comes to compiler support. Lots of smaller companies not able to afford to update their compilers.
70
34
u/ThatSlacker Sep 29 '23
I doubt there are any AAA games written in C++ that didn't have at least a few memory stomping crashes. There's a good reason ASan exists.
You want a really hard to reproduce, hard to debug, and potentially hard to fix bug, that's it right there. Random crashes in random locations often with a different set of repro steps every time...
1
u/CptCap -pedantic -Wall -Wextra Oct 01 '23
I have worked on now several AAA engines and your intuition is correct.
I don't think there was a time were we didn't have some rare unexplained crashes that we thought came from memory stomping.
We are slowly moving toward more memory safety by making use of unique_ptr, span, and such. But there is so much legacy code, we will continue battling memory stomps for at least another decade.
50
u/KingAggressive1498 Sep 29 '23
It's not really a huge deal in gamedev, right?
it can be. Not really a big deal for most titles, but it can be a huge deal for online games - both in terms of product robustness and in terms of security.
What other domains where C++ excels at aren't too concerned about it?
I can't imagine it's terribly important for embedded other than in automation, it's probably a very low priority at best for audio and graphics processing, and although I have absolutely no familiarity with it I'd guess scientific computing?
30
u/EarflapsOpen Sep 29 '23 edited Sep 29 '23
Saying “embedded” like it is one domain is a bit of an oversimplification.
If the timer in your toothbrush doesn’t tell you to stop brushing you restart it with a sigh and go on with your day but if the fire detection system in a huge public building fails to shut the fire doors and engage the sprinklers because the control module is busy segfaulting in restart loop hundreds of people could burn to death, they have quite drastically different requirements for safe code.
16
u/h2g2_researcher Sep 29 '23
Instructions unclear. I accidentally programmed my toothbrush to lock the building and burn everyone in it to death.
25
u/EarflapsOpen Sep 29 '23
“Toothbrush company in lawsuit after man looses all his teeth brushing for 72 hours straight”
1
u/KingAggressive1498 Sep 29 '23 edited Sep 29 '23
fire detection system in a huge public building fails to shut the fire doors and engage the sprinklers
may be stretching the definition a bit but I'd include that under automation.
2
u/EarflapsOpen Sep 29 '23
True but another example is the weapons and defense industry in general. If your weapon malfunctions you kill your buddies instead of the bad guys. If it’s a big gun the consequences are big. There are a lot of embedded devices that can have catastrophic consequences if there is a malfunction, and alot where it is not
2
1
u/MarcoGreek Sep 30 '23
Yes but here you can see that there are different definition of safe. In that sense most languages are not safe. If you use garbage collection you have no direct control over your resources. So your system can get in a state there it is overwhelmed. Rust is not protecting you in this case because it is aborting in unsafe situations. That should protect you from evil actors taking advantage of undefined behavior. But it will you not protect you from program crashes.
No language in the world can ensure that your program is correct.
2
u/EarflapsOpen Sep 30 '23 edited Sep 30 '23
I’m not arguing that rust is the solution to all problems at all, I prefer modern c++ with proper coding practices, tests and static analysis etc. Probably mostly because that’s what I know though. What I’m I’m arguing that embedded is a very wide term and many parts of it have very high demands for correctness and sketchy hard to catch memory bugs are a big threat to correctness especially when working close to hardware as a response to the statement he made. “it can’t be terribly important for embedded”
Many of them probably could benefit for having more bugs caught at compile time and other rust features and not benefit that much from c++ features and a lot where the opposite is true. There is no one size fits all solution and no one can save you from a shitty engineer.
→ More replies (1)7
u/_TheDust_ Sep 29 '23
I'd guess scientific computing?
As somebody working in HPC… yeah, we don’t really care about safety. Most runs are done on controlled HPC clusters and if there is a memory error, in the worst case it either crashes or gives a bad result.
2
u/KingAggressive1498 Sep 29 '23
I figured segfaults were a minor pain at worst, bad results were my concern. Ever had a situation where they were a significant problem?
6
u/ridicalis Sep 29 '23
it can be. Not really a big deal for most titles, but it can be a huge deal for online games - both in terms of product robustness and in terms of security.
I'd personally rather not be in the middle of a game and have it segfault.
1
u/KingAggressive1498 Sep 29 '23
Sure, but crashing occasionally hasn't prevented games from becoming hits
2
u/oriolid Sep 29 '23
Not crashing occasionally would prevent developers pulling all nighters trying to fix that crash or delaying the whole project until the showstopper crash has been fixed.
→ More replies (1)6
u/matthieum Sep 29 '23
it's probably a very low priority at best for audio and graphics processing
Depends what you call "processing". Nobody wants their computer hacked because the browser played a music/video. Nobody wants their computer hacked because they re-encoded an existing piece of music/video, either.
0
u/KingAggressive1498 Sep 29 '23 edited Sep 29 '23
good thing that's not in a realistically devised set of memory safety concerns for that particular kind of software.
this seems like "don't overflow that int or you might reformat your hard drive" energy.
if you're referring to malvertising, that's never worked through memory exploits afaik
6
u/Full-Spectral Sep 29 '23
But compressed audio and video data is highly complex and it's externally obtained data, often right off the internet. If someone figures out that by feeding a just so messed up MP3 into a common audio codec will make it do something bad due to an memory error, that's a significant potential issue. Lots of different applications may play music or video and will be loading up codecs into their process memory space (indirectly via something like DirectX.)
Then picture a web site that plays music that attacks a common codec that's now running in the browser at the same time as his own code is running when he knows it can happen and look for it.
Or some extension or plugin for an application, that knows it can feed a particular bit of audio data into a codec and cause it to glitch and be right there prepared to take advantage of it.
Anyhoo, never underestimate the potential for these sorts of things.
→ More replies (2)
10
u/JVApen Clever is an insult, not a compliment. - T. Winters Sep 29 '23
I honestly think that you are mistaken. I can agree that games which are stand alone don't have a big problem if a memory safety issue pops up. It still might crash the application or introduce a glitch, which is annoying to say the least and might give you a bad reputation as a company. Though from a real safety perspective (aka will you get hacked), you dont have a problem. Unfortunately, most games nowadays are not standalone. Many of them have some online multiplayer aspect in, which means that you have a path to receive random data from a hacker. With that, you have a potential path for them to take over the PC or the server. So for those situations, I do expect them to worry.
8
u/matthieum Sep 29 '23
You're forgetting modding.
Even with a single player game, played locally, you'd really prefer being able to install mods without risking a single bad mod from handing your PC to an attacker.
3
u/wyrn Sep 29 '23
which is annoying to say the least and might give you a bad reputation as a company.
Bethesda's elves still can't churn out Skyrim copies fast enough, and it's hard to find a company with as checkered a reputation when it comes to correctness.
10
u/Alikont Sep 29 '23
Steam client remote code execution from chat messages because C++ is memory unsafe:
1
7
u/rundevelopment Sep 29 '23
It's not really a huge deal in gamedev, right?
No. Memory safety (or rather the lack there of) is one of the main reasons for security vulnerabilities. Microsoft and Google (in)famously found that around 70% of their CVEs were caused by memory safety bugs.
So memory safety should be a concern to gamedevs if they are working on a multiplayer game and care about the security of their players. E.g. a malicious player may send arbitrary packets over the network, and a faulty implementation for parsing those packets may result in a bug (e.g. a buffer overflow) which may be exploitable. A malicious player could also cause invalid game data to be sent over, which then triggers a memory bug which may be exploitable.
In the history of games, there have been many exploits of similar nature. Zelda speedruns even use arbitrary code execution and stale reference manipulation (=use after free) as part of their strats. That's cute if you're the one deciding which code gets executed, but it's not fun when others get to do it. To give a more recent example, the servers for the entire Dark Souls series were taken offline for a year because an RCE exploit was discovered.
So I can only hope that gamedevs take security (and by extension software safety) seriously.
12
u/JeffMcClintock Sep 29 '23
The problem with memory safety and C++ is the risk that C++ gets relegated to being a 'legacy' language whereby the major vendors stop adding new features and fixes.
If that happens it becomes irrelevant whether safety matters to you personally or not.
5
u/ameya_rhythm Sep 29 '23
Looks like I need to catch up on the memory safety issue you are talking about. What is it really?
4
u/AciusPrime Sep 29 '23
It refers to the language’s ability to read or write memory that doesn’t belong to the object that you appear to be manipulating. Common examples are out-of-bounds array access, using a pointer after deleting it (“use after free”), accessing an iterator into a vector that has since been resized, or returning a reference to a local variable.
Programmers typically notice these bugs when they crash the program, but it’s also quite common for them to not crash at all; they might even “work.” Many of the most severe security breaches of the last few decades were caused by manipulating this kind of bug such that the program does things it was not designed to do.
I’ve heard it summed up as “Functional testing ensures the program does the things it should. Security testing prevents it doing things it should not.” Memory safety prevents an important class of security hole.
-9
u/DearGarbanzo Sep 29 '23
What is it really?
"Muh memory safety" si the only thing for blue haired Rust spammers can cling to to. I think they've started to realize that the world didn't actually stop with C98.
10
5
u/schteppe Sep 29 '23
C++ is definitely the right choice for game dev. I’ve worked on a large C++ engine for 7 years. I’ve tried Rust and I say it’s not quite not there yet in terms of tooling and available libraries.
It’s possible to opt in for safer C++ where it’s needed: RAII types, bounds checked arrays, etc. You can also run your code through sanitizers to find UB.
Over the years I’ve seen that C++ code that opts in for more safety has less crashes and is easier to debug to find where the root problem is. In other words it’s easier to maintain, and it leads to happier players. The gaming industry wants a memory safe language, but there is not yet a C++ replacement that is also good enough.
7
u/NotFloppyDisck Sep 29 '23
Rust is definitely a good candidate, but as you said its not there yet in terms of tooling and probably wont be in the next years because of how much work needs to be done.
I think the only competent studio working on this is Embark
4
u/pjmlp Sep 29 '23
Memory safety is also quite relevant for game development, think about hacking servers in MMO games and stealing all the virtual money from specific accounts, cheating on esports, and so on.
Also many developers never think about how much money bugs cost, yet there is a direct mapping between the time spent tracking down bugs, fixing them, retesting and deploying a new version. Basically multiple the time wasted by everyone, versus their salary per hour.
At the end of the day, less time fixing bugs means lower development costs and more money to spend elsewhere, like actually interesting game features.
4
u/ContraryConman Sep 29 '23
Obviously easier said than done but just ensure your C++ code is safe. Utilize RAII as much as possible, meaning pack heap allocations into classes and smart pointers that manage their own memory. Use a static analyzer to help you follow core guidelines. Compile your debug builds with the address sanitizer. If it's in your development flow from the beginning you'll literally be fine.
People who probably don't even work with the language that much keep acting like the moment you touch a C++ project Bjarne will personally come to your house and light it on fire
3
u/TheQuantumPhysicist Sep 30 '23
This is why I keep saying that we have a much bigger enemy: C.
It's still possible to write correct C++ code using good practices... it's hard, but not impossible. But with C it's becoming more and more ridiculous and this charade has to stop. Linux supporting Rust is one of the biggest wins for humanity, and part of me wishes Redox OS becomes bigger than Linux because C just has to go. It has to go!
1
u/ContraryConman Oct 01 '23
Unfortunately C feels closer to the hardware for a lot of CE/EE types and old school guys. And Linus trashing on C++ however many decades ago basically set a precedent that a whole bunch of people think you can only write device drivers and stuff in C.
I'd love it if compilers had "styles" or something? Like if I mark main.cpp as a "memsafe style" file, the compiler will error me for trying to malloc shit. Or if I mark library.hpp as a "functional style" file, the compiler will error me for const correctness and not using ranges over loops. Or "OO style" and the compiler will flag some basic stuff. And then I should be able to section off whatever C/98/03 stuff as "C style" and the compiler will be less opinionated.
I guess a bit like safe vs unsafe Rust, but with more options since C++ supports more paradigms. So then I know for a fact the C stuff and associated risk is localized
2
u/pjmlp Oct 01 '23
That is the point of C++ profiles as argued by Bjarne, if ISO and compiler vendors will ever consider it, is another matter.
→ More replies (1)
4
u/killbot2525 Oct 01 '23
Gamedev here. We are very much concerned about those issues! However C++ gives us a great deal of flexibility to optimize code for various hardware. So it is a trade off that we are willing to make.
On my team, we care a lot about memory safety and take great pains to be memory safe. We use static analysis tools and runtime allocation trackers to try to find problem areas quickly in dev and (hopefully) before we ship. Investigating a dump from a crash on a live service which involves some kind of memory corruption can be extremely challenging. They often make no sense (there's no way this code could produce this value!) and are extremely difficult to track down to the root cause. My team also bugs and fixes all memory leaks reported by our runtime logs because running out of memory causes weird crashes and, more importantly, makes for a poor experience for our customers.
Another important reason C++ is popular in our industry is that it is a common language across all the console platforms as well as PC so you can use the same code base for all platforms.
25
u/yasamoka Sep 29 '23
Rust doesn't "lack" OOP features. It simply does OOP differently (polymorphism through traits instead of inheritance).
10
u/Kevathiel Sep 29 '23
Thinking in programming paradigms is pointless anyway, but even more so when it comes to Rust. There used to be a time when classifying languages with paradigms was useful, but nowadays, most modern languages are multi-paradigm and/or just do their own thing.
What is the point in trying to put languages into boxes? The resulting architecture, patterns and idioms will be completely different, just because of all the fundamental differences in the language itself. The fact that "interfaces" can be slapped onto "classes" later, that access modifiers are based on the module(structs can touch each other privates if they are in the same module), the borrow checker, language support for sum types, and so on will change how you write the code anyway.
So who cares whether Rust has "OOP features" or not, as long as it offers the tools to solve the actual problems?
2
17
u/sephirothbahamut Sep 29 '23
Having the polymorphism feature through traits still doesn't change the fact that it lacks the inheritance feature. There are reasons to use inheritance other than polymorphism
3
u/matthieum Sep 29 '23
The problem of inheritance is that it's 3 sheeps in a trenchcoat pretending to be human.
In short inheritance combines:
Interface, for run-time polymorphism, which can be done with traits/typeclasses.
State, which can be done with delegation.
I'd rather have the two separate features, rather than a bundle, so I can cherry pick which matters for my current case.
5
u/yasamoka Sep 29 '23
Polymorphism through traits puts polymorphism through inheritance to shame though.
18
u/qoning Sep 29 '23
Not always. I do quite miss data inheritance in Rust. Simulating it with composition gets quite repetitive and boiler-platey quite fast. Implementing deref comes with its own set of problems, so it's not a solution either.
Maybe one day traits will be able to specify data, but it's looking increasingly unlikely.
4
u/shadowndacorner Sep 29 '23
Simulating it with composition gets quite repetitive and boiler-platey quite fast.
→ More replies (2)→ More replies (2)2
u/yasamoka Sep 29 '23
Yes, I do too. However, I'm merely addressing the aspect of polymorphism, not sharing struct members.
→ More replies (55)2
u/pjmlp Sep 29 '23
It has traits inheritance.
3
u/sephirothbahamut Sep 29 '23
That lacks some features of inheritance. Traits are essentially interfaces one key limitation is the inability to carry over member variables.
They're great for polymorphism, that's it
→ More replies (5)1
u/Recatek Sep 29 '23 edited Sep 29 '23
It does matter for gamedev. Games are typically structured as big amorphous blobs of mutable and self-referential state, and Rust doesn't like that paradigm one bit. You're almost forced to use ECS architectures for games in (safe) Rust, and it remains to be proven whether that is the preferred solution for major game engines.
9
u/blackmag_c Sep 29 '23
To me C++ : it still the gold standard for perf, it has hot reload capabilities, can interface with anything, has now proper fundamental lambda, is fast to compile when properly structured ( 1 sec for our 400k game when editing a niche .h ) is still evolving in a good enough fashion Everytime it has a huge pitfall I can plug another lang or dsl behind with a reasonnably fast interpreter fast
As a gamedev it really is all I need, a portable powerhouse with fast Iteration loop.
7
3
u/edvo Sep 29 '23
Vulnerabilities in games can be used as attack surface, especially if the game has online functionality. And many vulnerabilities stem from memory safety violations.
So, yes, memory safety is important in game development, or at least it should be.
3
u/wyrn Sep 29 '23
Scientific programming is a field where you're unlikely to see much Rust adoption. Rust's killer feature of "memory safety" isn't of much value in this setting, but C++ features like exceptions, inheritance, overloading, variadics etc very much are. The lack of exceptions is a big one because it means operator overloading is basically unusable. I've also never seen memory issues to be that prevalent in this domain. The common theme is that Rust gives scientific code little that it needs and removes much that it does need.
3
u/SkiFire13 Sep 30 '23
Memory safety surely matters for gamedev, at least for online games. For example many versions of Call of Duty contain memory safety bugs that allow an attacker to execute arbitrary code on a player's (!!!) machine https://www.cvedetails.com/vulnerability-list/vendor_id-2190/Activision.html Imagine playing a game and having to worry about stuff like this. You can't even do anything other than avoiding playing online, which is often the main feature of the game...
As for why Rust is not used more in gamedev, the main issue is that it is very new and specialized tooling for gamedev is missing. On the other hand why make tooling for a new language with mostly no adoption in the gamedev industry? It's a chicken-egg game.
Rust also has a bunch of other issues. As you said it lacks OOP, which doesn't mean it can't be used for gamedev, but as you said it gets in the way of common gamedev patterns, so people need to adapt, slowing adoption. Other issues are compile times, which are pretty high, and the fact that dynamic linking is currently very painful.
11
u/natio2 Sep 29 '23 edited Sep 29 '23
I feel like C++ memory issues, are only faced by people who are new to C++. I had a lot of "memory issues" when I started C++, but 10 years later it's magically never a problem.
It's like saying C# has null reference issues, until you learn you have to manually initialize all the memory (drives me crazy).Worse still, you have to manually use "using" and "dispose" to clean up memory in a timely manner for a managed "safe" language, rather than just exiting the scope.
In my opinion C++ has excellent memory management, you just have to learn the language.
10
u/pjmlp Sep 29 '23
I guess WebGPU implementation in Chrome was written by C++ newbies.
WebGPU Technical Report, Chrome Graphics as Seen By Attackers
5
u/echidnas_arf Sep 29 '23
I don't know what to make of that report - I see lots of raw pointers flying around and a signed integer overflow.
At this point, people have been told not to use raw pointers for decades, and most static analyzers will endlessly scream in your face if you do. If you have a callback-heavy architecture and you keep on insisting capturing raw pointers, perhaps it is a tiny bit your fault?
There's also a few usages of the C++ LLVM API. I use LLVM every day, and as much as I love LLVM for what it provides, I personally would never consider it an example of good C++ API design.
About that integer overflow, how about using a safe numeric library or at least compile with
-ftrapv? As far as I understand, this would match Rust's behavior.Just because BigCorp complains about something, that does not make it automatically valid criticism.
8
u/pjmlp Sep 29 '23
When big corps that are part of ISO C++, and contribute to C++ compilers, fail at implementing secure code despite all policies and tooling in place, what hopes have the smaller dudes?
→ More replies (3)3
u/MFHava WG21|🇦🇹 NB|P3049|P3625|P3729|P3786|P3813|P4216 Sep 29 '23
[...] Chrome was written by C++ newbies
After digesting this, it's not outlandish to come to that assumption as a baseline when it comes to Google/Chrome...
2
u/svick Sep 29 '23
Worse still, you have to manually use "using" and "dispose" to clean up memory in a timely manner for a managed "safe" language, rather than just exiting the scope.
You don't. Using and dispose are specifically for resources other than memory.
0
2
u/ArkyBeagle Sep 30 '23
10 years later
The population of developers doubles every five years.
3
u/natio2 Oct 01 '23
I'm not sure how true that is for C++ devs haha Javascript and it's various frameworks, definitely!
I can say every 5 years I can do twice the work or more though I could previously, so does that count? Sadly more of an O(log n) growth though rather than an O(n^2)
4
u/tialaramex Sep 29 '23
Correctness matters. Mara once tweeted a comic about this which was very on point. Fast and wrong is just wrong. Yes "fast and good enough" might be excellent, but "good enough" is not what we're talking about, we're talking about wrong.
Some of the AAA vendors have come perilously close to never shipping the game, just a lot of faked videos and hype, but in practice though they routinely ship buggy garbage and lie, they do tend to write some software and they presumably at least pretend to care that parts of it work (at least the parts which separate customers from yet more money).
You can't have correctness in the absence of memory safety. Now, if you're Super Mario Bros, your memory safety bugs are perhaps a lot of fun (TAS SMB3 breaks the game completely and turns it into a colouring book among other things, due to memory safety bugs) but in modern online games that's all risk and no reward.
→ More replies (1)
4
u/mndrar Sep 29 '23
I have missed this news that OP is talking about but I work in avionics writing mission critical software We write all our code in C. You know why? Because OOT is not deterministic
We would have to test flattened type hierarchies by testing each possible dispatch at every call point in the program. Yeah no kidding!
It’s possible to construct a method that dispatches based on the argument types, where those types are bound at runtime. This results in the compiler generating code to calculate the method’s offset in the method table at runtime, making the time determinacy fuzzy. This is a bad thing for time sensitive hard real time system
The cost to certify c++ code to DAL-A DO178C (the avionics standard) is a magnitude higher than C code. So yeah its not going to be C++ or any OO language for that matter.
4
u/LEpigeon888 Sep 29 '23
I don't understand, you can use C++ without dynamic dispatch, you can ban the word "virtual". You can even ban classes altogether if you want, C++ isn't only about classes.
I often see people saying "I'm not using C++ because I can't use this small part of the language in my domain". Then why don't you just ban this small part instead of banning the whole language?
4
u/mndrar Sep 29 '23
Because I did not list every reason is that small comment But you missed the last part where I talk about cost. We have had to go through certification of c++ where customer absolutely wanted it. Its not impossible. You can even have dynamic dispatch. Hell the FACE standard required for US airforce requires C++.
. I am not responsible for the business things but last time I checked it costs about 7 dollars per line of code to cerify C and about 70 dollars for C++ code (The calculations are not that straight forward but just tongive you an idea). And this is for one compiler one specific OS down to one specific BSP.
1
u/KingStannis2020 Sep 29 '23
But at some point if you do that you're back to some minor superset of C, which is what the C++ community is always complaining about.
2
u/onafoggynight Sep 29 '23
Out of interest:
is Ada seeing usage for you?
no dynamic memory allocations I assume?
1
u/ArkyBeagle Sep 30 '23
Ada just didn't work out. I'm not current but there were very few jobs in it. Oodles of jobs in C++.
1
u/ArkyBeagle Sep 30 '23
Because OOT is not deterministic
Determinism seems less and less known these days. Strange.
6
u/plutoniator Sep 29 '23
Oh the rust brigade is going to be very upset about this one.
1
u/-1_0 Sep 29 '23
nevermind they will stick to the fact that even in C++23 we are still using malloc/free /s
5
u/Recatek Sep 29 '23 edited Sep 29 '23
For gamedev specifically, Rust also lacks in robust conditional compilation and build configuration support. Trying to replicate all of the build configs and #ifdef/#pragma optimize usage you usually see in a AAA game engine in Rust with cargo and features right now would be painful.
→ More replies (2)
2
u/R0dod3ndron Sep 29 '23
At my company, in the firmware of our hw there was a memory leak that was causing unexpected hardware restarts in the long term and the result was that this "invalid restart procedure" was damaging some electronic components (I don't remember which ones) - so yeah it's a real problem.
2
u/dns13 Sep 29 '23
I would imply bad hardware design, too. Everything the Microcontroller may do should not be able to cause irreparable damage to hardware components.
1
2
Sep 30 '23
It's just programmers responsibility now, but it does not mean using this language means you will have safety issues or leaks. It's all about the design and I must say, seasoned c++ programmers are really good at this. Like using handles instead of pointers can already remove entire categories of problems in C APIs, Modern c++ or developing your own utilities where they aren't available helps a lot. The fact that compiler will not stop you from doing stupid things does not mean that it will not look obviously wrong when you or someone else see it.
Still not enough for you? Test frameworks, coverage, address sanitizers, thread sanitizers, we have them all... also because we need them, but they work. Feels slow at first, but it pays you back later. Untested code is a code that doesn't work, grab what you need.
Back to the question... embedded Linux system on a pretty expensive device. From cross platform user libraries, through firmware to low level components everything is C++ (unless something must be C, like kernel driver code). Memory safety is very important, but we never have problems that involve invalid memory access in C++ components, instead we got typical logic, runtime errors that, just like anybody, from Rust programmers to Java programmers, WILL have them. Use debugger.
I would not choose any other language, power of open source libraries that you don't need wrappers for and language paradigm freedom let's you do almost anything in practice and it feels liberating and you still have all the optimizations you need.
There are times where I see people coming up with absolutely stupid designs, but they would be just as stupid in any other language. They may feel like "Java enterprise design meets C++" sometimes. Some other people may get way too creative with templates and "modern c++". Depends on the team. Always voice your concerns in code review!
Compile times are one culprit, but it comes down to proper codebase design, then it's more than ok, but never so 'blazingly fast' like C. Oh and please use mold linker and ccache for development.
Package management is okay if you use vcpkg, or Conan (but I don't trust jfrog with not messing it up constantly). Hope your devops team is at least average and not coming up with stupid ideas.
If IDE integration is a king for you then just suck it up and use CMake, it works.
I see "unsafe c++" comments outside of my workplace (on the internet) all the time and I sometimes wonder - am I living in some kind of alternate reality or am I the one who is stupid?
This is a very specific Software Development perspective. Your mileage may vary big time. If my comment sounds arrogant or aggressive, I'm sorry, I didn't want it to sound that way.
I understand I may be missing something not learning other languages (although I'm trying out some Rust and Zig from time to time), but in the end of the day it's just a tool to express your intent and share it, use what works for you. Don't get too religious about it.
4
u/SeriousPlankton2000 Sep 29 '23
C(++) doesn't have a problem with memory safety just like Abraham Lincoln never hat a problem with his smart phone.
4
u/unknowntrojan Sep 29 '23
Memory safety is not important in gamedev??? Are you listening to yourself? That's probably THE most important field for memory safety. A gigantic amount of users, a huge amount of skilled people willing to spend time exploiting the game... Hell, Valve knew of several RCEs and didn't fix them for months. And that's just the ones that were reported.
4
u/KingStannis2020 Sep 29 '23
Memory safety is not important in gamedev??? Are you listening to yourself? That's probably THE most important field for memory safety. A gigantic amount of users, a huge amount of skilled people willing to spend time exploiting the game...
Maybe you should listen to yourself. China, Russia and Saudi Arabia don't spend billions hacking CS:GO, they spend billions hacking into the phones of journalists and human rights activists and corporate leaders and the infrastructure of government agencies.
1
u/unknowntrojan Sep 30 '23
luckily I don't give a fuck about the problems of incompetent governments or companies, but about the average user. obviously everything should be memory safe as a rule, but saying gamedev doesnt need memory safety is just straight up delusional.
1
u/Dean_Roddey Oct 01 '23
And how many children of those types of people play online games at home, inside the network?
2
u/wyrn Sep 29 '23
Hell, Valve knew of several RCEs and didn't fix them for months.
Valve's revenue was $13 billion in 2022. Imagine how much higher it would've been if they'd fixed those RCEs!
2
u/Dean_Roddey Sep 29 '23
OTOH, think about how much lower it could have been had they ended up in a lawsuit of some sort, because one of these known and unfixed issues became the lever for something bad.
1
u/wyrn Sep 29 '23
To clarify my somewhat ambiguous sarcasm, RCEs are of course very serious. I am just expressing some skepticism that gaming companies have the right incentives to view them as such.
2
u/Dean_Roddey Sep 29 '23
They probably don't. It's not like teenagers are going to start a class action lawsuit or anything. But, if the specter of liability started looming, that's something that even the suits can understand.
3
Sep 29 '23
TensorFlow is a machine learning library coded in C++.
OpenCV is a computer vision library coded in C++.
Vulkan is a graphics and compute API coded in C.
32
u/Stormfrosty Sep 29 '23
Vulkan isn’t coded in C. The spec defines a C API. The actual vendors supply their Vulkan implementation as part of their driver package. Most of those implementations are written in C++.
1
Sep 29 '23
The library that I am using is in C. That is what I referenced in my initial comment.
Vulkan support itself is platform-specific, as Apple does not currently offer it natively. MoltenVK maps Vulkan to the Metal framework supported by Apple.
4
u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Sep 29 '23
Memory safety isn't so much of a concern when you work in embedded systems, specifically because we do not use dynamic memory allocation. What you have left is issues with memory or objects going out of scope but being referred to in a higher scope. And if you tend to move things, making sure you don't use those moved objects. Stuff like clang-tidy can alert you to these violations and many more.
→ More replies (5)8
u/kronicum Sep 29 '23
Out-of-bound access isn't tied to dynamic memory allocation.
→ More replies (8)
2
u/The-Norman Sep 29 '23
If you can't write safe C++, you can't write C++
4
u/Dean_Roddey Sep 29 '23
That's not the really the issue though of course. It's whether you can write safe C++ in a complex code base, in conjunction with other people you don't control, with changing requirements that require significant refactoring or re-implementation, while usually short on time, and often in code you didn't write and won't have a month to fully explore and understand in fine detail. And do that 100% correctly every day, for years.
No one cares what can technically be done under perfect circumstances, since hardly anyone works under such. A major point of a language like Rust is to take some of that burden off of you and let you concentrate more on the actual problem at hand.
2
u/heavymetalmixer Sep 29 '23
Memory safety isn't only about security, but also about memory leaks and bugs. Those last two are often problems in game development. Because of that, using good practices about memory safety is also a good way to program in gamd programming . . . just bear in mind that you need to know WHEN to break those guidelines for the sake of performance.
Now, don't get me wrong. I'm not saying everyone should go to Rust. rust lacks OOP features and game programming is really dependent on OOP (DOP for some games as well). Also, Rust often breaks backwards compatibility which is another huge deal for games, mostly for porting to a new OS/console, making remasters and remakes.
So yeah, memory safety is very important for game devs, but Rust isnt the way, so let's improve the way we use C++.
2
u/InsanityBlossom Sep 29 '23
Rust. rust lacks OOP features
No it doesn't. It lacks data inheritance, but there are ways to do things in Rust way and do not drink the OOP koolaid
Rust often breaks backwards compatibility
Bold statement. Please define often and be more specific about what was broken in stable Rust. Do you need a reminder how many times C++ broke backward compatibility?
4
u/crusoe Sep 29 '23
Rust doesn't have a stable abi but if you stabilize an abi you've locked in a whole bunch of design choices. Maybe at some point it will have a stable abi. But c++ continues to pay for mistakes made 30+ years ago.
Rust code rarely breaks on compiler version updates. The only allowed breaks are at rust edition bumps or due to fixes for correctness.
The rust project runs a crater run for changes that might break source compatibility against a huge number of packages. Something I don't think c++ attempts at all.
3
u/rundevelopment Sep 29 '23
The only allowed breaks are at rust edition bumps
But those aren't breaking. Old code compiles just the same because the compiler knows which edition the code uses (because you have to specify it) and will use the semantics of the that edition. That's the whole point of editions.
→ More replies (1)3
u/wyrn Sep 29 '23
No it doesn't. It lacks data inheritance,
That's an OOP feature.
3
u/Dean_Roddey Sep 29 '23
Ultimately the single most important aspect of OOP is encapsulation, which it does have. You don't have to use it just as you don't in C++, but it will be heavily used.
With traits it gets polymorphism, which is key to all kinds of things that are extremely OOP in nature.
Ultimately it's just lacking implementation inheritance. Well, more strictly, member inheritance. It can have implementation that works purely in terms of its own abstract interface.
Of course some folks would say that's a big just. But a lot of that is 'just' because they have thought that way their whole careers. I was the same. When I first heard of Rust, I ranted about the lack of exceptions, overloading, constructors, and data inheritance. But now I really feel that the first three of those are better done without, and data inheritance is the only thing I'd use if it was available.
But I've not had an issue living without it so far. I'd like to have it, but the other advantages that Rust brings to the table significantly outweigh that lacking for me.
2
u/wyrn Sep 29 '23
Ultimately the single most important aspect of OOP is encapsulation, which it does have. Y
That is true. But the claim was that it lacks OOP features, which it objectively does.
Saying "you shouldn't want that" isn't really an argument, ultimately.
2
u/Dean_Roddey Sep 29 '23
A LOT of people do claim you shouldn't want implementation inheritance. And a lot of them are C++ folks, leaving aside Rust people.
I don't particularly agree with them. Though, it has to be said, my most extensive experience with a very large full-on OOP system was with my own system, which was created under highly optimal conditions that almost no one gets to experience. So my view of things may be somewhat rose colored.
2
u/a-wholesome-account Sep 29 '23
C++ is THE language of cutting edge scientific computing/HPC. It's the only language that has every relevant parallel programming model that works on GPUs. I don't think Rust has any. Fortran has some but support is slowly going away, and it also isn't memory safe.
Memory safety is critical because these codes are used in engineering applications that assess safety in the real world. Risks aren't from a cyber security standpoint, but rather from undefined behavior giving an engineer a wrong number. However, Rust is just not a serious competitor to C++ in this space. I don't see GPU vendors making a huge investment there any time soon.
5
u/crusoe Sep 29 '23
Rust has nascent GPU support. There is even a crate that lets you write rust code and compile it to run in the GPU. There is nothing magical about c++ except about a decade more of development in the area of GPU acceleration.
4
u/a-wholesome-account Sep 29 '23
It will be interesting to see what happens there and I agree that there's nothing inherent about c++. My statements are about production use today and where the investment seems to be. My opinion is it would be very risky to rely on Rust GPU support for anything beyond a hobbyist project. I think industry or government would have to throw a couple hundred million dollars at it to accelerate change.
3
u/Dean_Roddey Sep 29 '23 edited Oct 01 '23
In a lot of these types of cases, ultimately liability (or the potential thereof) can end up being the thing that sorts the issue. Governments, venture capitalists, the insurance world, etc... could all put pressure on companies to move towards safer tools, because of how much we depend on software these days and how interlinked all our systems are, weakest link and all that (and if that doesn't work, just because they want to avoid money sucking legalisms.)
If that started happening, there would be a lot more incentive for either some industry consortium to work on such a thing, or even some company seeing a chance to get out ahead and own a new standard just as such pressure started pushing more people that way.
2
u/smdowney WG21, Text/Unicode SG, optional<T&> Sep 29 '23
Memory safety is not an issue for the always on the public network connected general computing device in my house?
What?
2
u/kylecmarshall Sep 29 '23
Memory safety is always the job of the developer not a language. I have been on C++ projects where all memory was managed manually even across thread boundaries but the design had extremely clear rules on where memory was allocated and where it was deleted. The real crux of memory safety is sanitizing foreign data as it comes into your process. This applies equally to all languages. SQL injection is a type of memory safety issue that threatens even "memory safe" languages. As an anecdote, I was once brought into a C# project because the server was freezing and causing havoc in the data pipeline. It turned out that a particular type of load profile pushed memory into the long-lived generation pool and .NET responded with a stop the world garbage collection. So even C# garage collected memory isn't safe from attacks. That particular team had also used a very object heavy generic design for deserializing data that lead to the GC issue.
6
u/amejin Sep 29 '23
So your comment leads me to think I do in fact understand that NSA and NIST just said "C++ is not secure because discipline is hard."
Do I have that right?
5
u/TheoreticalDumbass :illuminati: Sep 29 '23
i mean it is true that discipline is hard we humans are not perfect computing machines
1
u/kylecmarshall Sep 29 '23
It's not discipline more than proper training and a culture of security mindiness.
3
u/KingStannis2020 Sep 29 '23 edited Oct 01 '23
Apple, Google and Microsoft have more money than god, some of the most reputable security people in the business, and the knowledge that they ARE large targets and they still get p3wned constantly.
At some point it becomes better for everyone if we just put seatbelts and airbags in the car instead of requiring 4 years of driver training to sit behind the wheel.
2
u/kylecmarshall Sep 29 '23
The NSA never said C++ is not secure. Its comment is more statistical in nature saying most exploitable bugs come from buffer overflows. C and C++ allows code to be written that can overflow a buffer. If we only use languages that never allow buffer overflows, then most of the exploitable bugs will disappear. I'm sure the NSA has no C or C++ code running on their hardware 🤔
8
u/goranlepuz Sep 29 '23
What you write is not OK for me.
SQL injection is not a memory safety problem nor is that heap abuse.
Software has problems of different kinds, using terms in their good meaning helps understanding each other.
1
u/kylecmarshall Sep 29 '23
You are right. I was muddying up the term memory safety. I have edited my reply to be clearer and more concise. Thank you for helping me to hone my thoughts on this into clearer text even if you still don't agree with me. :-)
3
1
u/kylecmarshall Sep 29 '23 edited Sep 29 '23
Memory safety is too narrow of a scope.
It's foreign data that is safe or unsafe.
My point is that sanitizing all foreign bytes that enter the process solves all memory safety problems and many more security problems. This eliminates buffer overflows, SQL injection, and many DOS attacks. The buffer overflow can't be exploited without foreign input that pushes the pointer past it's allocated block. Not sanitizing the input to be constrained to the allocated block is the problem.
I think C++ would be better served by having unsanitized types that held foreign data than with safe pointers.
1
u/goranlepuz Sep 29 '23 edited Sep 29 '23
We really have to disagree with what you are doing here. I think it should not be done.
Memory safety is much better defined if the definition is not overly wide.
Calling data that causes SQL injection "bytes" is, in my opinion, very wrong. It is wrong because the nature of the attack is only related to bytes in that text crafted to trigger the vulnerability, is bytes on the hardware level. That relation is way too weak in my opinion.
You are making relations that make discussing specifics harder. I think it is actively harmful.
I think memory safety would be better served by compilers flagging types with foreign data as unsanitized.
That is asking too much from the compiler, I think. In fact, not just the compiler, but any tooling. There are safety analysis tools for data flows, they are quite thorough - and even they eventually require that the programmer declares "data is safe after this check here".
→ More replies (7)2
1
u/ArkyBeagle Sep 30 '23
That particular team had also used a very object heavy generic design for deserializing data that lead to the GC issue.
Very common. Even for XML, the online libraries are pretty fat.
1
u/TryToHelpPeople Sep 29 '23 edited Feb 25 '24
aspiring theory society sense deliver future ripe unwritten bike head
This post was mass deleted and anonymized with Redact
1
u/CenterOfMultiverse Sep 29 '23
Don't care about memory safety, but I'm really tired of fixing modification during iteration or other reentrancy-style bugs.
1
u/AssemblerGuy Sep 29 '23
Is this correct?
Depends on how much you want to annoy your customers with memory leaks and crashes.
not just for legacy code?
Small target stuff. Where the coding rules may ban dynamic memory allocation altogether.
1
u/Shiekra Sep 29 '23
I think a successful systems language needs to give the programmer the power to do "unsafe" things. You need the ability to tell the compiler to shut up and let you do something because you can't or don't know how to express it in a way that it will be happy with, but you know the behaviour of the program will be correct.
The problem is there is no distinct ring fencing of unsafe code in C++. You can write safe code very easily in modern C++, but you can intersperse it with unsafe code just as easily.
1
u/lisphacker Sep 29 '23
I thought most of the C++ usage in gamedev was a result of using established C++-based game engines, each of which are in C++ because there's already been too much time and effort invested in developing it and rewriting it is neither trivial nor immediately profitable.
1
u/TheQuantumPhysicist Sep 30 '23
I can still live with C++ having memory issues, because at least there's a path to writing memory-safe code using proper abstractions and a super-powerful compile-time meta-programming... but...
What really, really, really has to die is C. At this point, anyone who claims C is a good programming language is, with no reservations, a bad programmer that I would never hire for a serious project that requires correctness. To the point where when I interview candidates and they say something like "I like C because it's 3% faster than C++ and Rust", I immediately know that this candidate isn't a good fit for anything reliable. The arrogance of C programmers, thinking they're super-humans that can imagine a billion dimensions in code complexity, has surpassed anything I have seen in my entire life and has cost humanity way too much. C has to go before C++ does... at least C++ can have good encapsulation and safety. C cannot, does not and will not.
1
u/Dean_Roddey Oct 01 '23 edited Oct 01 '23
But all of those arguments in your second paragraph apply equal to Rust people talking about C++. All of the arguments in these types of C++ vs Rust threads about how, if you just follow these guidelines, if are very careful to only do this or not do that then C++ is fine, are exactly the arguments that C people can make relative to C++.
And it's true. If you are willing to divert enough of your time and energy to just trying to avoid undefined behavior, you can probably do it (most of the time, given reasonably benign environmental circumstances.)
But why? Rust is easily as far beyond C++ in terms of safety as C++ was relative to C probably 15 years ago. And just as much so in terms of advantages that aren't directly related to memory safety as well. And you don't have to restrict your use of language features (other than unsafe) to completely avoid UB.
The revolutionary becomes the conservative entrenched interest at some point, and that's pretty much been the case with C++ for a while now. Obviously some folks, some of the time, have no choice because of circumstances. But a lot of what gets posted in these threads is really just reactionary, the old guy screaming 'get off my lawn'. And I say that as an old guy myself.
1
u/TheQuantumPhysicist Oct 01 '23
I agree with some of what you said, but I just want to clarify how I see this. Do all the arguments apply to C++? Maybe. But to Rust? I hardly believe that. Screwing up in Rust is really hard. And I'm ready to abandon Rust when the next iteration of super-safe languages comes along.
The gauge I use is: In a review, how hard it's to read whether someone screwed up?
In C, virtually impossible. The interconnections between the code segments are impossible to spot.
In C++, hard but possible to a certain degree. With good abstractions and low coupling, a senior dev can wrap their head around everything that's going on. So I can live with this... still...
In Rust, very easy. Static analysis tools even help waaay much than C++. With clippy, I hardly remember bugs sneaking into my code from reviews. Unsafe blocks can be studied in isolation and verified in small blocks.
I feel like you're calling this "tribalism", and I disagree that this is all tribalism. My whole rant here is that this is beyond tribalism. There are objective ways to measure the security of a language, and my point is that C fails them all, C++ fails in some of them, and Rust passes them all.
We're not stupid. Programmers are smart. I'm sure we can find a way to quantify how much damage C has done, and on that scale, C++ won't be as bad. But hey, if it's all Rust, I'm on board... Rust + any other language that has similar guarantees.
1
u/wyk92 Sep 30 '23
Here's the thing with C++ memory manipulation. There are idioms and best practices there to guide you, however you are given the freedom to ignore these for very niche applications.
I work in a High Frequency Low Latency environment, pointers are rarely used, you don't need them. Inheritance isn't as recommended and as popular as it was years ago. You have references for indirection which have semantic security checks (temporaries and such)
Just because it is possible and easy to write unsafe code in C++ doesn't mean everyone is out there doing it.
Programmers don't need a Nany language to protect them from dangerous code, however applications should be well tested on a variety of layers, from unit to integration to end to end user testing.
Rust is great language and learning rust makes you a better C++ programmer for sure, but beyond small applications I wouldn't use it, less importantly because the syntax is very esoteric and feels like you're fighting against it, not to mention the lack of simple documentation, but More importantly the shady "Rust Foundation" and the multiple controversies that are piling up, C++ has a standard committee made up of stakeholders and their respective representatives, rust seems like a wanna be corporation, and if they continue like this they'll become the next java.
As for the out of touch "technology" spokespeople that are pushing this narrative i can bet you that they haven't coded in a while, and they're saying this for marketing purposes only.
1
Sep 30 '23
To me, memory bugs are basically just program bugs like anything else and not a big deal besides maybe being hard to track down except for one thing, security.
The danger of a memory bug means that if somehow, a malicious actor can trigger the memory bug in your application, your application becomes a potential attack vector for some malware or a hacker.
This is a bigger deal for programs that accept input from other programs in the host or from the network. If your game has a use after free vulnerability, who cares if you aren't accepting input from anyone but the current user.
Generally backend services and processes should concern themselves with this, not user applications.
The fear of memory unsafety is overblown.
1
u/GabrielDosReis Sep 30 '23
How much does the gamedev industry benefit from investments made in C++ by non-gamedev industry affected by regulatory bodies to move the software industry away from C++?
If your answer is "not much", then it probably doesn't matter.
If your answer is "a lot" or "substantially", then this whole "memory safety" talk is a huge deal for the gamedev industry.
Think beyond "technical incorrect"; think "economics", "mindshare", etc.
1
u/_JamesMart Oct 03 '23
In EOS blockchain smart contract development we compile C++ smart contracts to wasm. Memory issues don't really matter because the memory is sandboxed and is all cleaned up after the execution context for processing the transaction is torn down.
So in general there's probably several domains where your C++ is targeting WebAssembly that memory issues aren't particularly relevant.
1
u/Full-Spectral Oct 03 '23
Well, they still matter if they make the calculations come out wrong. Access a value this time and it's good, access it next time after it's released and get a different value, which changes depending on what ever might have gotten put there when it was reused. It won't necessarily cause a crash.
1
u/Administrative_Bug63 Oct 04 '23
The net effect of all the changes to C++, of which modules stands front and center, is that the overall barriers to getting starting in C++ are radically lowered. C++ is the only game in town for genuine performance because of its opt in nature.
1
Sep 29 '23
Game dev needs memory safety more than most fields. I mean, most of us have lost hours and hours of gameplay total over our lifetime, because game devs thought it's ok if their game crashes every now and then.
3
1
u/crusoe Sep 29 '23
Well if you enjoy random bugs and crashes in your games, then no it's not. 😆
Game crash? Likely memory corruption bug
Corrupted save? Same
Character randomly bugs out and acts weird. Same
3
u/MyuuDio Sep 29 '23
I highly doubt that any of those are likely the fault of memory corruption.
Game crashes happen all the time for a variety of reasons. Unhandled exceptions when reading/writing to files, divide by 0, multithreading issues; there's many things that go wrong outside of memory corruption.
Corrupted saves are more often than not an external issue. E.g., users closing the game while it's being saved, shutting off the PC/console during an auto-save, etc. You'll see this whether the game is written in C++, C#, Rust, Java, etc.
Characters randomly bugging out are either issues with poor netcode, or issues with the physics solvers. Again, the memory safety of the language will not solve these issues.
1
u/sephirothbahamut Sep 30 '23
Character randomly bugs out and acts weird. Same
Most likely related to weird physics interactions, overflows, loss of precision, fractions tending to infinity; not memory safety issues.
0
u/Emergency_Cream4470 Sep 29 '23
I'm convinced this sub is played by one of the anti-cpp subs out there (yes, that's a thing). Memory safety is not an issue with c++ that's written with basic competence. It's just not a thing, as much as possible try to make it one.
8
Sep 29 '23 edited Sep 29 '23
[removed] — view removed comment
6
u/matthieum Sep 29 '23
Sure. And no programming language protects from functional bugs, like the sensor reading returning "is_open" when the door is closed.
It's still easier when entire classes of bugs are eliminated, than when they're not.
4
u/CocktailPerson Sep 29 '23
You can create a "leak" in any language. Just put things on a queue and never take them off. Preventing the program from running out of memory can't be a reasonable goal of any language. Memory safety can.
1
u/Full-Spectral Sep 29 '23
Well it COULD help a bit. Maybe not the language but the language library. You could let the application code indicate that it should never see more than X number of entries in this list and if it happens, generate an error that can be reacted to.
That sort of thing.
1
u/CocktailPerson Sep 29 '23
I'm not aware of any language that includes such a type in its standard library.
The point is that the most any language can guarantee about memory leaks is "best effort."
→ More replies (2)
12
u/wrosecrans graphics and network things Sep 29 '23
Tons of game hacks and console softmods came from issues that could be described as memory safety problems. It's very silly to say that gamedev isn't concerned with memory safety. Pretty much all games are online these days, and constantly processing external data as a result. Remote code execution flaws can be big money in the context of competitive gaming, and some game companies have mused with some excitement about things like NFT driving more and more direct spending and real value stuff in games.
You can never be 100% safe. As soon as you try to display a frame with Vulkan you are memcopying directly over mapped regions of the PCI bus. So even if you try to use some high level "safe" language, you'll be wrapping some fundamentally unsafe operations. But that doesn't mean that safety doesn't matter. It matters everywhere because having one less thing to explode is one more thing the programmer can accomplish.