개요
Rust에서는 컴파일러 수준에서 댕글링 포인터를 방지할 수 있습니다.
Rust에서 댕글링 포인터를 차단하는 방법을 알아보세요.
댕글링 포인터란?
해제된 메모리 영역을 가리키는 포인터를 자유 포인터라고 합니다.
아래와 같은 코드가 있습니다.
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int *b = &a;
int *c = &a;
cout << a << endl;
cout << *b << endl;
cout << *c << endl;
}

여기서 B가 메모리를 해제하면 A의 메모리도 해제됩니다.
#include <iostream>
using namespace std;
int main()
{
int a = 5;
int *b = &a;
int *c = &a;
cout << a << endl;
cout << *b << endl;
delete b;
cout << *c << endl;
}

여기서 C는 정지 포인터가 되지만 해제된 메모리를 가리키기 때문에 오류가 발생합니다.
C 또는 C++의 경우 런타임 시 확인할 수 있습니다.
녹 대 C++
다음 예제는 C++로 작성된 예제입니다.
string* dangle()
{
string* s = new string();
return s;
}
int main()
{
string* reference_to_nothing = dangle();
cout << *reference_to_nothing << endl;
}
C++에서는 런타임에 reference_to_nothing에 값이 없다는 것을 알고 있습니다.
Rust에는 언어에 그런 매달린 포인터가 없습니다. 컴파일러에 의해 필터링됩니다.
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
위 코드의 오류 메시지입니다.
error(E0106): missing lifetime specifier
--> dangle.rs:5:16
|
5 | fn dangle() -> &String {
| ^^^^^^^
|
= help: this function's return type contains a borrowed value, but there is no
value for it to be borrowed from
= help: consider giving it a 'static lifetime
error: aborting due to previous error
s는 dangle 내부에서 생성되었으므로 dangle의 코드가 끝나면 s가 해제됩니다. 그러나 우리는 그것에 대한 참조를 반환하고 싶었습니다. 이것은 이 참조가 유효하지 않은 문자열을 가리킨다는 의미가 아닙니다! 아주 좋은하지. Rust는 우리가 그렇게 하도록 허용하지 않을 것입니다.
