Python is memory safe? Can’t you access/address memory with C bindings?

  • onlinepersona@programming.dev
    link
    fedilink
    English
    arrow-up
    60
    arrow-down
    8
    ·
    6 months ago

    Mr Stroustrup can spin it however he likes, but 70% of CVEs are caused by memory errors in unsafe languages like C and C++. That isn’t happening because the majority of their devs are idiots. The language is the problem.

    Talking about “but there are tools” and “hold on a minute, there a ways to write safe C++” is missing. It’s way too easy to write memory unsafe code in C++. The opposite is true of other languages and that’s why they are being recommended (dare I say pushed) over C++. To write memory unsafe Rust for example, you really, really have to want to.

    C++ is his baby, Of course he won’t acknowledge it and it was entirely predictable he would blame the programmers. The language will be the equivalent of COBOL in a decade or two.

    CC BY-NC-SA 4.0

    • Technus@lemmy.zip
      link
      fedilink
      arrow-up
      36
      arrow-down
      1
      ·
      6 months ago

      If “just don’t be an idiot” worked in the real world we wouldn’t have any need for laws or safety regulations or certifications. It’s not and never has been a compelling argument.

      Writing C++ is like walking around a construction site without a hard hat and going “ah I don’t need it, I’ll just make sure nothing falls on my head.” Yeah sure, buddy, we’ll make sure that’s written on your tombstone.

  • Feathercrown@lemmy.world
    link
    fedilink
    English
    arrow-up
    45
    arrow-down
    3
    ·
    edit-2
    6 months ago

    $100 says his response boils down to “just don’t write unsafe code”

    Edit: It did. He also said C++ is working to implement optional safety features, but tl;dr:

    Of the billions of lines of C++, few completely follow modern guidelines

    And the modern guidelines are mostly an unenforced list of things not to do.

    • merthyr1831@lemmy.world
      link
      fedilink
      arrow-up
      22
      arrow-down
      2
      ·
      6 months ago

      doesnt enforce memory safety damn all these stupid devs dont know how to write memory-safe code!!!

    • porgamrer@programming.dev
      link
      fedilink
      arrow-up
      16
      arrow-down
      2
      ·
      6 months ago

      Even following the guidelines, modern C++ is just a huge pile of half-finished ideas. It goes pretty well for the first few hundred lines of code, and then you hit a very basic problem where the solution is “yes this will work great in C++26, if the proposal doesn’t get delayed again”.

      • lysdexic@programming.dev
        link
        fedilink
        English
        arrow-up
        2
        arrow-down
        7
        ·
        6 months ago

        Even following the guidelines, modern C++ is just a huge pile of half-finished ideas.

        You’re making it pretty clear that you are completely oblivious to what C++ is, what are the differences between C++ versions, and what are the real world issues solved by each new version.

        I would ask you to clarify your persona clams by providing a concrete example to back each of your statements, but I know you have none.

        • porgamrer@programming.dev
          link
          fedilink
          arrow-up
          5
          arrow-down
          1
          ·
          6 months ago

          Lol okay. Here are some concrete examples I don’t have:

          Templates as basic generics

          • Templates still show bizarre error messages far too deep into instantiation, despite at least three major features which provided opportunities to fix the problem (static_assert, type_traits, and then concepts)

          Templates for metaprogramming

          • 33 years after the introduction of templates, there are still many common cases in which the only good way to abstract a pattern is by using a macro, and many cases that neither macros or templates can solve
          • There is finally an accepted proposal to fix part of the problem, which will be introduced in C++26, and probably not usable in real code until 2030 at the earliest
          • In 2035, people will still be reluctantly using string macros and external code generation to solve basic problems in C++

          Safe union types

          • C++17, std::variant was introduced to provide a safe inline union type
          • The main API for accessing it is inexplicably slow, unlike in every competing language
          • The fast alternative is an eyesore that can’t integrate with switch statements except via weird, unmaintainable hacks
          • Everyone keeps using custom struct/union/enum combos instead
          • CVEs everywhere

          Error handling

          • C++ uses exceptions as the primary error handling mechanism
          • Exceptions are so slow and so riddled with problems that some companies ban them, and almost all consider them bad practice for representing common failure paths (e.g. failing to parse something)
          • std::expected eventually approved, similar to Rust’s Result type, but with no equivalent to the ‘?’ operator to make the code readable
          • Now there is a proposal to introduce “value type exceptions” instead, which is gathering momentum before std::expected has even stabilised, but will probably not be available for 10 years

          Subtype polymorphism deprecated

          • Now that virtual methods and inheritance are widely considered tools of last resort, they obstruct the introduction of better alternatives
          • Instead we have widespread use of specialised template structs and CRTP to replace instance inheritance with a kind of static inheritance designed for templates
          • It’s all a hack, and as a result it’s full of edge cases that don’t work very well, and poor tool support

          References

          • Good C++ programmers use references where possible, because pointers can be null
          • Good C++ programmers avoid unnecessary copies and allocations
          • Good C++ programmers avoid patterns that can permit unintended coercions with no error
          • Oh no, I accidentally assigned a reference to an auto variable in a template, and instead of giving a helpful type error it implicitly coerced a new copy of my vast memory buffer into existence
          • Okay fine I’ll pass pointers to avoid this, and just trust they won’t be null
          • Oh no, C++ has standardised the idea that raw pointers represent nullability even in all their newest standard library types (thanks again, std::variant)
        • orangeboats@lemmy.world
          link
          fedilink
          arrow-up
          4
          arrow-down
          2
          ·
          6 months ago

          I think if you consider anything post C++03 (so C++11 or newer) to be “modern C++” then Concepts must be the top example, doesn’t it?

          Counting from C++0x that’s almost a decade of waiting.

  • BehindTheBarrier@programming.dev
    link
    fedilink
    arrow-up
    37
    arrow-down
    4
    ·
    6 months ago

    Why wait and hope for C++ to get where modern languages are now? I know there’s value in the shared experience in C++ that if adapted would make it stronger, but I can only see a development of C++ having to force a drop of a lot of outdated stuff to even get started on being more suitable.

    But the language is just not comfortable to me. From large amounts of anything creating undefined behavior, the god awful header files which I hate with a passion, tough error messages and such. I also met a fun collision of C++ in Visual Studio and using it with CMake in CLion.

    I’ve just started looking at rust for fun, and outside not understanding all the errors messages with the bounded stuff yet, figuring out what type of string I should use or pass, and the slow climb up the skill curve, it’s pretty nice. Installing stuff is as easy as copy pasting the name into the cargo file!

    Rust is just the prospective replacement of C++ though, people act like the White house said that C++ should be replaced by rust now. But the just recommend it and other languages, C# will do for a lot of people that does not need the performance and detail that the aforementioned languages target. Python is targeting a whole different use, but often combined with the faster ones.

    C++ will live a long time, and if the popularity dies down it will surely be very profitable to be a developer on the critical systems that use it many years from now. I just don’t think an evolution of C++ is going to bring what the world needs, particularly because of the large amount of existing memory related security vulnerabilities. If things were good as they are now, this recommendation would not be made to begin with.

    • arendjr@programming.dev
      link
      fedilink
      arrow-up
      16
      arrow-down
      2
      ·
      6 months ago

      I totally agree with this comment, and on top of that I would recommend anyone who really cares about the current state of affairs regarding safety in C++ to read this overview: https://accu.org/journals/overload/32/179/teodorescu/

      Quote:

      Personally, I am not convinced that in the near future, C++ can do something to stop this trend. C++ will leak talent to other languages (currently Rust, but perhaps in the future to Cppfront, Carbon, Hylo or Swift). If the progress towards safety started in 2015 as Bjarne suggested, the last 8 years have seen very little progress in safety improvements. Even with accelerated efforts, the three-year release cycle and slow adoption of new standards will keep C++ a decade away from addressing major safety concerns.

  • litchralee@sh.itjust.works
    link
    fedilink
    English
    arrow-up
    35
    arrow-down
    2
    ·
    6 months ago

    I’m not a Rust developer (yet), but I understand its strength in this regard as: Rust is statically memory safe by default, and code which isn’t statically memory safe must be declared with the unsafe keyword. Whereas C++ has not deprecated C-style pointers, and so a C engineer can easily write unsafe C code that’s valid in a C++ compiler, and no declaration of its unsafeness is readily apparent to trigger an audit.

    It’s nice and all that C++ pioneered a fair number of memory safety techniques like SBRM, but the debate now is about safety by default, not optional bolt-on safety. All agree that the overall process to achieve correct code is paramount, not just the language constructs.

    • snowe@programming.devM
      link
      fedilink
      arrow-up
      44
      arrow-down
      9
      ·
      6 months ago

      It’s also just a huge fallacy. He’s saying that people just choose to not write memory safe code, not that writing memory safe code in C/C++ is almost impossible. Just look at NASA’s manual for writing safe C++ code. It’s insanity. No one except them can write code that’s safe and they’ve stripped out half the language to do so. No matter how hard you try, you’re going to let memory bugs through with C/C++, while Rust and other memory safe languages have all but nullified a lot of that.

      • MajorasMaskForever@lemmy.world
        link
        fedilink
        English
        arrow-up
        20
        arrow-down
        1
        ·
        edit-2
        6 months ago

        As someone who is in the aerospace industry and has dealt with safety critical code with NASA oversight, it’s a little disingenuous to pin NASA’s coding standards entirely on attempting to make things memory safe. It’s part of it, yeah, but it’s a very small part. There are a ton of other things that NASA is trying to protect for.

        Plus, Rust doesn’t solve the underlying problem that NASA is looking to prevent in banning the C++ standard library. Part of it is DO-178 compliance (or lack thereof) the other part is that dynamic memory has the potential to cause all sorts of problems on resource constrained embedded systems. Statically analyzing dynamic memory usage is virtually impossible, testing for it gets cost prohibitive real quick, it’s just easier to blanket statement ban the STL.

        Also, writing memory safe code honestly isn’t that hard. It just requires a different approach to problem solving, that just like any other design pattern, once you learn and get used to it, is easy.

        • 0x0@programming.dev
          link
          fedilink
          arrow-up
          1
          ·
          6 months ago

          I’d’ve thought Ada would play a larger role in aerospace, because of these issues, among others.

        • snowe@programming.devM
          link
          fedilink
          arrow-up
          1
          ·
          6 months ago

          Also, writing memory safe code honestly isn’t that hard. It just requires a different approach to problem solving, that just like any other design pattern, once you learn and get used to it, is easy.

          the CVE list would disagree with you.

        • arendjr@programming.dev
          link
          fedilink
          arrow-up
          2
          arrow-down
          3
          ·
          6 months ago

          Also, writing memory safe code honestly isn’t that hard. It just requires a different approach to problem solving, that just like any other design pattern, once you learn and get used to it, is easy.

          This statement is kinda ironic after you just said it’s “easier” to just ban the entire STL and dynamic memory allocation as a whole. You already left the domain of what most consider “easy” quite a while ago.

      • zik@lemmy.world
        link
        fedilink
        arrow-up
        2
        arrow-down
        2
        ·
        edit-2
        6 months ago

        It’s also a fallacy that rust code is memory safe. I audited a couple of large rust projects and found that they both had tens of unsafe constructs. I presume other projects are similar.

        You can’t use “unsafe” and then claim that your program’s memory safe. It may be “somewhat safe-ish” but claiming that your code is safe because you carefully reviewed your unsafe sections leaves you on the same shaky ground as c++, where they also claim that they carefully review their code.

        • calcopiritus@lemmy.world
          link
          fedilink
          arrow-up
          2
          ·
          6 months ago

          I don’t have the data, but I don’t think it’s wild to assume that most rust programs have 0-1 unsafe blocks, in total. Except for special cases like ffi.

          Even if your rust project has 1000s of unsafe blocks, it is still safer than C++, which is 100% an unsafe block. You only have to carefully review the parts marked “unsafe”, in C++ you have to carefully review the whole code.

          Also, because unsafe blocks are explicitly declared, you know which parts of the code require extra carefulness, and if you encounter a memory bug, doing Ctrl+F “unsafe” will soon show the root cause.

  • merthyr1831@lemmy.world
    link
    fedilink
    arrow-up
    30
    arrow-down
    3
    ·
    6 months ago

    He can get mad all he likes but there’s a reason the Linux kernel’s experiment with rust is going much smoother than C++ (which only lasted a literal week btw)

  • cook_pass_babtridge@sh.itjust.works
    link
    fedilink
    arrow-up
    13
    ·
    6 months ago

    I’d love to see Bjarne Stroustrup being grilled by Congress about this, and have to explain shared pointers and reference counting to the same people who didn’t understand how Facebook made money.

  • Rikj000@discuss.tchncs.de
    link
    fedilink
    English
    arrow-up
    33
    arrow-down
    22
    ·
    edit-2
    6 months ago

    TLDR: But-hurt C++ dev has a hard time accepting that his favorite language is not memory safe.

  • words_number@programming.dev
    link
    fedilink
    arrow-up
    26
    arrow-down
    20
    ·
    6 months ago

    Kinda sad how that guy destroys his reputation so late in his life. I mean he actually contributed a lot to the field of software development, but just refuses to accept that C++ days are thankfully over. The language has grown into a complete abomination, but all the experience we gained during its long history (good and bad) are extremely valuable for designing new languages from now on. One can’t rescue a design by just adding things to it (regardless of the kind of design), that’s just a simple truth. Thus, a backwards compatible C++ can never become even half as good as rust is already today (and there’s of course always room for improvement). But that’s not because bjarne did something stupid, but because humanity as a whole didn’t know better back than. He could just accept that, embrace new technology, retire in dignity, be remembered as highly admired and appreciated. Instead he acts like a butthurt idiot, trying to defend that cars shouldn’t have seatbelts, because if everyone drives carefully, nothing bad will happen anyway. Pathetic.

    • mox@lemmy.sdf.org
      link
      fedilink
      arrow-up
      16
      ·
      6 months ago

      One can’t rescue a design by just adding things to it (regardless of the kind of design), that’s just a simple truth.

      This statement could also be applied to Perl, PHP, JavaScript, and most other languages that eventually add new ways of doing things, especially if they preserve backward compatibility. I’m not sure that this is a condemnation of C++ so much as an inevitable consequence of being successful for a long time.

      To be clear, I’m not defending C++. Just pointing out that it’s not unusual in this regard. I have no doubt that Rust will also have vestigial warts in time, if it doesn’t already.

      • Corbin@programming.dev
        link
        fedilink
        English
        arrow-up
        5
        ·
        6 months ago

        You are very close to a deep truth of language design: all large popular languages slowly die from committees overloading them with cruft and redundant features, and at the end of their healthspans, they become painful for all involved. In your list, this includes both PHP and ECMAScript; Perl 5 avoided this fate, but Raku certainly suffers from it.

    • Cirk2@programming.dev
      link
      fedilink
      arrow-up
      5
      arrow-down
      2
      ·
      edit-2
      6 months ago

      Bringing more modern tools and features to existing large code bases is “destroying his reputation”? Bjarne and the committee is constantly extending and modernizing a language with code bases older than me. Yes that means the old stuff has to be kept around but that is the price of allowing existing code to migrate gracefully instead of just throwing it out of the window. There is a problem with some missing rails to enforce current and saver techniques but Bjarne is not denying that.

      • words_number@programming.dev
        link
        fedilink
        arrow-up
        5
        ·
        6 months ago

        Bringing more modern tools and features into C++ is good. Acting as if that would make it equally suitable for new projects or even equally safe as languages that don’t (yet) suffer from carrying around a ton of legacy garbage nobody should use (both in terms of features and std items) is ridiculous though.

  • signor@lemmy.world
    link
    fedilink
    arrow-up
    6
    arrow-down
    1
    ·
    6 months ago

    So how fucked am I for starting to learn cpp as my first language, or is this a later down the road thing to worry about?

    • thomask@lemmy.sdf.org
      link
      fedilink
      English
      arrow-up
      9
      ·
      6 months ago

      If you can write correct C++ you’ll be able to write Rust code that compiles first time. Don’t stress, you’re learning the good stuff.

    • lysdexic@programming.dev
      link
      fedilink
      English
      arrow-up
      6
      arrow-down
      1
      ·
      6 months ago

      So how fucked am I for starting to learn cpp as my first language, or is this a later down the road thing to worry about?

      I don’t see why you should be concerned, except that no professional software developer is limited to use one specific programming language.

      Even if you pay attention to the disaster prophets in the crowd, which are mainly comprised of fanboys implicitly and explicitly promoting their pet language/frameworks, C++ dominates all aspects of the computing ecosystem, which means that in the very least the whole world needs to maintain existing C++ projects to continue to work. See COBOL for reference.

    • seth@lemmy.worldOP
      link
      fedilink
      arrow-up
      4
      ·
      edit-2
      6 months ago

      I think it’s a good first language to learn. Because it’s a lower level language than most of the popular ones these days, you will learn a lot of interesting concepts and problems you wouldn’t otherwise get or even need for higher level stuff - like memory management, allocation, garbage collection and cleanup, and pointer references - but which give you a better understanding and appreciation for what’s in the black box.

      But you also learn a lot of transferable concepts like typing, mutability, objects and object oriented design, polymorphism, etc. And there are still a ton of jobs where C++ knowledge is required or at least useful.

      I have barely touched it over the years since first using it, but patterns and approaches I learned in C++ have come in handy for me a lot when troubleshooting and when reading other people’s code, and being able to recognize who is going to be a helpful person to talk to when I run into problems I can’t quickly figure out.

    • zygo_histo_morpheus@programming.dev
      link
      fedilink
      arrow-up
      3
      ·
      6 months ago

      There will be plenty of jobs in c++ in the foreseeable future, so it’s not a bad language to know from that perspective. I don’t know if it’s the most pedagogical language to learn otoh, python is a better language for getting comfortable with the basics, c is better when it comes to learning a (slightly wrong but close enough) mental model of how a computer works under the hood, and there are many better languages to learn if you want to learn good approaches to thinking about problems.

      Maybe you are leaning c++ because you want to work on something specific that c++ is primarily used in, and in that case go ahead with that project. I think having something tangible that you want to work on is great when it comes to learning programing and that’s worth more than picking the “best” language. Besides, you can always learn different languages later in your career if you want/have to.

  • qprimed@lemmy.ml
    link
    fedilink
    English
    arrow-up
    6
    arrow-down
    16
    ·
    edit-2
    6 months ago

    heh! so glad I intentionally avoided C++ from the get-go. C when I want to blow some fingers off quickly, python when I want to stroll down a country lane picking flowers. there is no in-between ;-)

    • solrize@lemmy.world
      link
      fedilink
      arrow-up
      7
      ·
      6 months ago

      C++ is nicer to use than C, and with currently preferred style it’s safer, though not safe in the way Python is.

      You might also try Go and Ada. I confess to not having clear understanding of how Rust beats Ada or vice versa. There are very few people really knowledgeable about both, who have addressed this afaik. I can say coding in Ada feels clanky but very solid. Idk yet about Rust.

      • qprimed@lemmy.ml
        link
        fedilink
        English
        arrow-up
        1
        ·
        6 months ago

        thanks for the reply. C++ never really clicked for me. I started out decades ago with C and enjoyed living on the edge with older hardware and OSes - when neither the OS nor the hardware will defend itself from an application, things get real fun, real fast.

        as PC hardware matured, python filled in the safety spaces when needed and I eventually just used python with C bindings to balance speed and safety as needed for any particular project.

        I have never seriously looked at ada, but your comment piqued my interest, so I may just play with it for a bit. Go… what can I say about Go… like C++ its just feels “odd” to me. cant really explain why, perhaps it just feels too… “google”?

        I am going to be taking some time to really try groking Rust over the next 6 months… from what I have seen so far, Rust is the language that I wanted C++ to be so many years ago… fills in many more gaps and gives an expansive playground for various types of projects - many of the benefits of python-like and C-like languages in a nice, unified space.

        would love to get your thoughts on that if you have time.

        • solrize@lemmy.world
          link
          fedilink
          arrow-up
          2
          ·
          6 months ago

          Go is totally different from Rust. It has garbage collection and built-in lightweight threads with message passing, but a fairly simple type system comparable to C’s.

          Rust and post-2011 C++ have fancier type systems influenced by e.g. Haskell. If you haven’t used such languages before, there may be a learning curve, but that temporary confusion you’ll feel is the sensation of your brain getting bigger, so it’s a good effort to make.

          Rust and C++.afaict are mostly designed for systems programming where you want to control resources and memory manually. If you can stand a larger footprint, you might be more productive in a GC’d language. That said, I haven’t used Rust yet. Lots of Haskellers like it though.

          For Haskell, try learnyouahaskell.com .

          For Ada, try http://cowlark.com/2014-04-27-ada/index.html and then “Ada Distilled” (online book, use web search).

          • qprimed@lemmy.ml
            link
            fedilink
            English
            arrow-up
            1
            ·
            6 months ago

            thanks for the excellent reply. will check out all of your links.

            I do like built-in light weight threading, so Go is still on the to-play-with list and I am currently tracking a few Go projects to get my feet wet.

            you have given me options and impetus to get out of my decades long rut and, honestly, that is the best gift any programmer can give to another. thank you, friend.

            • solrize@lemmy.world
              link
              fedilink
              arrow-up
              2
              ·
              6 months ago

              You should also look at Erlang and Elixir (same VM, different surface syntax). They have some similarities with Go but aim at higher reliability in the presence of faults. Erlang was originally designed to run phone switches, and it was a critical requirement that the switch keeps running even if some part of it goes wrong.

          • lolcatnip@reddthat.com
            link
            fedilink
            English
            arrow-up
            1
            ·
            6 months ago

            I’m not a fan of Go, but calling its type system comparable to C is unfair. C has nothing like Go’s interfaces, and Go has generics now. Plus having strings and maps as built-in types is a huge win for convenience. Go’s slices are also superior to how arrays are usually done in C (but still a lot less ergonomic than a C++ vector or Rust Vec).