본문 바로가기

Rust Programming

[Rust] 7. Leaking memory

spawned thread에 references를 넘기는 것에

가장 큰 문제가 use-after-free bugs다.

 

use-after-free bugs는 이미 free됐거나 de-allocate된 memory영역을

pointer를 통해 접근하는 것이다.

 

만약 heap에 할당된 data를 다룬다면,

그 memory를 절대 회수하지 않을 것이라고 Rust에게 알려줌으로써,

이 문제를 피할 수 있다.

즉, 의도적으로 메모리 누수를 선택하는 것이다,

 

Rust standard library의 Box::leak method를 통해 할 수 있다.

// Allocate a `u32` on the heap, by wrapping it in a `Box`.
let x = Box::new(41u32);
// Tell Rust that you'll never free that heap allocation
// using `Box::leak`. You can thus get back a 'static reference.
let static_ref: &'static mut u32 = Box::leak(x);

 

Leaking data는 위험하다.

memory를 leaking상태로 둔다면,

결국 memory가 부족해져서 out-of-memory 오류로 인해

프로그램이 충돌하게 될 것이다.

// If you leave this running for a while, 
// it'll eventually use all the available memory.
fn oom_trigger() {
    loop {
        let v: Vec<usize> = Vec::with_capacity(1024);
        v.leak();
    }
}

 

동시에 leak method를 통한 memory leaked는 실제로 forgotten하는것이 아니다.

OS는 각 memory영역을 process에게 map할수 있다.

process가 exit할 때, OS는 memory를 되찾을 것이다.

 

아래를 기억해라.

leak memory는 아래와 같을 때, 가능하다.

  • leak하려는 memory의 양이 무한하지 않고 사전에 알 수 있거나
  • process가 단기간 실행되며, 종료되기 전에 사용할 수 있는 모든 memory를 다 소진하지 않을 것이라고 확신할 때

usecase가 허용된다면, OS에게 맡기는 것도 유효한 memory management 전략이다.

 


03_leak exercise는 이전과 method의 형태는 같으나 leak를 활용하는 것이었다.

leak함수를 사용하면 vector의 &'static mut [T]의 slice를 얻으며,

split을 통해 반반 slice를 나눌 수 있다.

 

해당 나눈 slice또한 &'static mut [T] slice이므로 thread에서 move keyword없이 사용 가능하여,

문제를 해결할 수 있었다.

 

 


 

이전 02_static에서 배운 내용과 많이 겹쳐 괜찮았고,

이해하기 쉬웠다.

'Rust Programming' 카테고리의 다른 글

[Rust] 7. Scoped threads, Channels  (0) 2024.10.30
[Rust] 7. 'static lifetime  (0) 2024.10.13
[Rust] 7. Threads  (0) 2024.10.12
[Rust] 6. HashMap, BTreeMap  (0) 2024.10.07
[Rust] 6. Index trait, IndexMut trait  (0) 2024.10.06