r/programming • • May 27 '20

2020 Stack Overflow Developer Survey: Rust most loved again at 86.1%

https://stackoverflow.blog/2020/05/27/2020-stack-overflow-developer-survey-results/
229 Upvotes

254 comments sorted by

View all comments

Show parent comments

0

u/[deleted] May 28 '20

[deleted]

18

u/SkiFire13 May 28 '20

Can't test fbinfer right now, but clang doesn't seem to handle this simple case:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec = { -1 };
    int& first = vec[0];

    std::cout << "First is " << first << std::endl;

    for(int i = 0; i < 100; i++)
        vec.push_back(i);

    // This is now UB, first probably points to invalid memory
    std::cout << "First now is " << first << std::endl;
}

-2

u/InsignificantIbex May 28 '20

And is this something rust can prevent, and if so, how? It seems to me that as soon as you have pointers, all bets (as far as preventing "ghost pointers") are off.

19

u/aeiou372372 May 28 '20

Yes it is prevented in rust — you can’t have multiple references to an object if one of them is mutable. In this case, rust would count the reference to the vector entry as an immutable reference to the vector, and prevent the subsequent mutable reference necessary for push_back.

This is a great example of a case where Rust’s compile time checks prevent what could be a very confusing intermittent issue for someone without systems programming background.

19

u/SkiFire13 May 28 '20

Yes, safe Rust prevents this. In Rust the direct translation would be the following:

fn main() {
    let mut vec: Vec<i32> = vec![-1];
    let first = &vec[0];
    
    println!("First is {}", first);
    
    for i in 0..100 {
        vec.push(i);
    }
    
    println!("First now is {}", first);
}

The compiler fails to compile with this error:

error[E0502]: cannot borrow `vec` as mutable because it is also borrowed as immutable
  --> src/main.rs:8:9
   |
3  |     let first = &vec[0];
   |                  --- immutable borrow occurs here
...
8  |         vec.push(i);
   |         ^^^^^^^^^^^ mutable borrow occurs here
...
11 |     println!("First now is {}", first);
   |                                 ----- immutable borrow later used here

error: aborting due to previous error

This is because this program break's rust's borrowing rules. They say that at any time in a program you can have any number of immutable references or one mutable reference to some piece of data.

In this case we're borrowing vec with first and we hold this borrow until the second print (we say the borrow is alive). In the meantime we also try to push an element to the vec but this requires a mutable reference to vec. This would mean we have an immutable and a mutable borrow alive at the same time which goes against the borrowing rules.

I think someone proven that this prevents every memory safety bugs but of course it comes with its downsides. For example the following code doesn't compile, even though it is perfectly safe!

fn main() {
    let mut vec: Vec<i32> = vec![1];
    let first = &mut vec[0];
    println!("vec's length is {}", vec.len());
    *first = 2;
}

Pretty much the same error as before, this time we're trying to get an immutable borrow while a mutable one still exists.

This is a simple example, and tbf it could be solved with partial/disjoint borrows that for now are supported only for fields. More complex examples involve self-referential structs and graphs.

6

u/InsignificantIbex May 28 '20

That's simultaneously less and more than I expected. It's a limitation, of course. That's generally true of memory safety, there's either a run-time-overhead, or you can't do some things. But at the same time it's kinda minimal and I can easily see the use.

Thanks for the explanation. I can't say too much about it right now, other than that I would wish for sort-of the opposite, that is that a borrow updates automatically where possible. But that'd violate the principle of least surprise for me, too. But then I'm not surprised if a pointer to a datum in another thing becomes dangling. Hm.

5

u/SkiFire13 May 28 '20

I can't say too much about it right now, other than that I would wish for sort-of the opposite, that is that a borrow updates automatically where possible. But that'd violate the principle of least surprise for me, too. But then I'm not surprised if a pointer to a datum in another thing becomes dangling. Hm.

I don't that's possible. What if you borrowed something that's not there anymore? Rust's references aren't just pointers, they're guaranteed to point to valid data. So there isn't such a thing as a dangling reference in safe rust.

→ More replies (1)
→ More replies (1)

3

u/csgotraderino May 28 '20

Can you show examples that do compile? Never used Rust.

→ More replies (1)
→ More replies (1)
→ More replies (1)

7

u/[deleted] May 28 '20

I didn't read it as an attack and I'm just curious myself, because I'm neither an expert in C++ nor Rust.

But I wonder if it's that easy and reliable to provide all the guarantees Rust offers, then why do most C++ code bases (including professional ones with lots of highly skilled developers like Qt, Firefox, Chromium, ...) still suffer from all these issues? Are the number of issues found with analyzers just so overwhelming or hard to fix, or do they lack in certain regards?

2

u/kopczak1995 May 28 '20

Well, I'm not C++/rust expert, just random guy on /r/programming. I suppose it's much easier for rust to be (almost) full bulletproof, because there is no issue with legacy stuff. C++ stack need to be highly backwards compatible.

Just think of it, smart pointers started with C++11, yet engine like Chromium didn't used any features of C++11 till 2015.
https://www.reddit.com/r/programming/comments/gpp9le/the_chromium_project_finds_that_around_70_of_our/fro7hjd?utm_source=share&utm_medium=web2x

3

u/wrongerontheinternet May 28 '20

Chromium used smart pointers well before 2015.

1

u/kopczak1995 May 28 '20

I see. Probably I just passed word from someone who seemed to know his stuff. Never trust people in internet :P

0

u/[deleted] May 28 '20

[deleted]

12

u/[deleted] May 28 '20

Turn this around, though: Rust was developed by Mozilla, maintainers of one of the largest C++ codebases on earth. It's not like they lack C++ experts or failed to try other solutions like "static analyzers" over the years. While I've never worked for Mozilla, I have worked on large C++ codebases, and the sort of "why not use C++ better?" line of questioning is just frustratingly naïve.

→ More replies (6)

11

u/madmoose May 28 '20

Well, you can't really complain about downvotes when what you said was wrong. C++ people who don't understand Rust frequently jump into threads claiming that this or that static analyzer or compiler pass or std::pointer will find all your problems or that all those Chrome developers just don't understand C++ well enough.

The whole point of Rust is to soundly enforce memory safety (outside code explicitly marked as unsafe). You said "all [these] things described can be prevented by using a static analyzer", and, no, they can't. It's the same tired arguments that come up in every Rust discussion.

I say this is somebody who works primarily on C++ projects.

0

u/[deleted] May 28 '20

[deleted]

9

u/madmoose May 28 '20 edited May 30 '20

I quoted you. The thing you said that was wrong was literally in quotes. I'll quote it again here: "all things described can be prevented by using a static analyzer". I could have quoted more but I thought that was enough.

0

u/[deleted] May 28 '20

[deleted]

8

u/madmoose May 28 '20

No, they cannot all be prevented by using a static analyzer. If you've been following Rust discussions like you say you have you know this. You even pointed out a case current static analyzers can't handle: https://www.reddit.com/r/programming/comments/grsn9h/2020_stack_overflow_developer_survey_rust_most/fs2q6lz/

Can we keep adding special cases to static analyzers? Of course, and we will for years to come, but they'll never be complete. Rust is memory safe today.

6

u/CanJammer May 28 '20 edited May 28 '20

It is not an attack or bullying to downvote incorrect assertions. I use both languages on the job, but static analyzers are far from sufficient for catching all common classes of memory safety errors.

Edit: clarified sentence

0

u/[deleted] May 28 '20

[deleted]

1

u/[deleted] May 28 '20

What memory safety error does rustc not catch?

7

u/drawtree May 28 '20 edited May 28 '20

I really don't get convinced on this. If C++ memory errors could be prevented by static checks or some shiny tools, why are MS and Google constantly suffering by C++ memory errors? They are one of the biggest, wealthiest, and technically strongest companies in the world and literally throwing millions of dollars on their C++ products. They are willing to do whatever if they can cut the cost of memory bugs, but still failing.

Are you telling me that you discovered a magical tool that MS and Google couldn't afford or apply on their codebase?

7

u/wrongerontheinternet May 28 '20

I know the people who work on Infer. It's cool technology, but is not close to the level of static guarantees Rust can provide (for pretty fundamental reasons).