값이 저장된 메모리 주소 얻기, 특정 메모리 주소에 저장된 값 얻기
요즘 같은 개발 환경에서 메모리의 주소를 직접 얻고 해당 메모리에 저장된 값을 읽는 코드를 …? 러스트 프로그래밍 언어에서 …
먼저 어떤 값에 대한 메모리 주소를 얻는 코드는 다음과 같습니다.
fn main() {
let a = 3224;
let mut memory_location = (&a as *const i32) as usize;
println!("데이터 저장 메모리 주소 : {}", memory_location);
memory_location이 3224 값이 바인딩된 a의 주소값을 담고 있습니다. 이제 memory_location 값(주소)에 저장된 값을 읽는 코드는 다음과 같습니다.
unsafe {
let v = *(memory_location as *const i32);
println!("메모리 주소({memory_location})에 저장된 값: {}", v);
memory_location += 4;
let v = *(memory_location as *const i32);
println!("메모리 주소({memory_location})에 저장된 값: {}", v);
}
}
메모리 주소를 통한 값의 직접적 참조는 매우 매우 위험한 행위이므로 반드시 unsafe 코드임을 명시해야 합니다.
