G
G
GeraZlo2021-12-03 15:57:35
Rust
GeraZlo, 2021-12-03 15:57:35

What is the reason for memory leak in rust program?

Memory is leaking in the rust program, I commented on pieces of code until I found that the memory was leaking due to the filter method.

The method accepts an rss structure and returns a bool indicating whether a news notification should be displayed or not.
It also saves the date of the last news output to the local file/database rustbreak.

I don't understand why there is a leak.

Filter sources:
https://github.com/NightStr/rust_rss_bot/blob/deve...

Program main loop:
https://github.com/NightStr/rust_rss_bot/blob/deve...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GeraZlo, 2021-12-04
@GeraZlo

Eliminated the leak by rewriting a large terrible function, in a closure into two small ones, taking all the logic out of the closure.
It was:

impl UserRssItemsFilter for FilterByLastRequestData {
    fn filter(&self, user: i64, rep: &String, item: &RssItem) -> bool {
        let key = format!("{} {}", user, rep);
        let r = self.last_request_cache.write(|db| {
            let last_request: DateTime<Utc> = if let Some(last_request_str) = db.get(&key) {
                DateTime::parse_from_rfc2822(&last_request_str).unwrap().into()
            } else {
                Utc::now() - Duration::days(2)
            };
            if last_request < item.created_date {
                db.insert(key, item.created_date.to_rfc2822());
                true
            } else {
                false
            }
        }).unwrap();
        self.last_request_cache.save().unwrap();
        r
    }
}

It became:
impl UserRssItemsFilter for FilterByLastRequestData {
    fn filter(&self, user: i64, rep: &String, item: &RssItem) -> bool {
        let key = format!("{} {}", user, rep);
        let last_request = match  self.last_request_cache.read(|db| {
            match db.get(&key) {
                Some(v) => Some(DateTime::parse_from_rfc2822(v).unwrap().into()),
                None => None
            }
        }).unwrap() {
            Some(v) => v,
            None => Utc::now() - Duration::days(2)
        };

        if last_request < item.created_date {
            self.last_request_cache.write(|db| {
                db.insert(key, item.created_date.to_rfc2822());
            }).unwrap();
            self.last_request_cache.save().unwrap();
            true
        } else {
            false
        }
    }
}

Y
Yo JLa, 2021-12-09
@blanger

For those who will read, but suddenly do not know. Rust can guarantee that there will be no "data race", but it cannot guarantee that there will be no "memory leaks" in all possible cases, although it contributes to this in a certain way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question