Hello, im currently trying to write a double linked list algorithm in rust and hit a roadblock, which is the difference of using Box::into_raw() and straight up use raw pointer when creating a node.
this is my code:
use std::ptr;
#[derive(Debug)]
struct Node{
prev:*mut Node,
val:i32,
next:*mut Node,
}
impl Node{
fn new(val:i32)-> Self{
Self{
prev:ptr::null_mut(),
val:val,
next:ptr::null_mut(),
}
}
}
#[derive(Debug)]
struct DoubleLinkedList {
head:*mut Node,
tail:*mut Node,
length:i32,
}
impl DoubleLinkedList {
fn new() -> Self {
Self{
head:ptr::null_mut(),
tail:ptr::null_mut(),
length:0,
}
}
fn add_at_head(&mut self, val: i32) {
let mut newnode:*mut Node=&mut Node::new(val);
//let mut newnode:*mut Node=Box::into_raw(Box::new(Node::new(val)));
unsafe{
if self.length==0{
self.head=newnode;
self.tail=newnode;
}else{
(*self.head).prev=newnode;
(*newnode).next=self.head;
self.head=newnode;
}
println!("{:?}",(*self.head));
}
self.length+=1;
}
}
let mut mylist:DoubleLinkedList=DoubleLinkedList::new();
mylist.add_at_head(1);
mylist.add_at_head(2);
unsafe{
println!("{:?}",(*mylist.head));
}
result with normal raw pointer:
Node { prev: 0x0, val: 1, next: 0x0 } //printing inside function add_to_head;
Node { prev: 0x7ffc006b7450, val: 2, next: 0x7ffc006b7450 } //printing inside function add_to_head;
Node { prev: 0x7ffbffeb8000, val: 7042288, next: 0x714a95a796e0 } //printing after insert
result with Box pointer:
Node { prev: 0x0, val: 1, next: 0x0 } //printing inside function add_to_head;
Node { prev: 0x0, val: 2, next: 0x616dbfd9bb10 } //printing inside function add_to_head;
Node { prev: 0x0, val: 2, next: 0x616dbfd9bb10 } //printing after insert
my question is :
1.when using normal raw pointer why is prev got set with a raw pointer? i dont even touch it. and in the box pointer its work as expected. is it a memory corruption or something?
- when accesing next inside the function why the code return the same node? for example when i access next for node with value 2 it should return "Node { prev: 0x0, val: 1, next: 0x0 }" instead it return "{ prev: 0x7ffc006b7450, val: 2, next: 0x7ffc006b7450 }"
3.after inserting, why is the whole pointer value changes? self.head should have the head of Node { prev: 0x7ffc006b7450, val: 2, next: 0x7ffc006b7450 } instead it become Node { prev: 0x7ffbffeb8000, val: 7042288, next: 0x714a95a796e0 }.make 0 sense
4.why box pointer work and normal raw pointer doesnt
i couldnt find anything regarding this problem, can anyone help me explain what happening here?
thank you