1

Here is the code:

pub struct Node<T> {
    data: Option<T>,
    level: usize,
    forward: [Option<*mut Node<T>>; MAX_HEIGHT],
}

And I want to iterate the linked list:

// let next = some_node.forward[n];
unsafe {
    loop {
        match next {
            None => { break; }
            Some(v) => {
                write!(f, "{:?}", (*v).data)?;
                break;
            }
        }
    }
}

When I use unsafe keyword, I get the [1] 74042 illegal hardware instruction cargo run error, so is there anyway to debug this unsafe block?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
McGrady
  • 10,869
  • 13
  • 47
  • 69
  • 1
    there is a lot of way of "debuging", this is too broad, this error mean you probably mess a lot with memory, you didn't provide an [mcve] so I will vote to close your question. – Stargateur Jan 25 '19 at 02:51
  • Probably dup/related: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – hellow Jan 25 '19 at 07:25
  • If your `Node` derives from `Debug` (hint: it should), you could try printing `next` with the new `dbg` macro: `match dbg!(next)`: at each iteration of the loop. – Matthieu M. Jan 25 '19 at 09:53
  • 1
    What's this `!v.is_null()` check? You immediately dereference `v` after the `if` check, so surely it's never null, right? If it is never `null`, then consider using [`ptr::NonNull>`](https://doc.rust-lang.org/std/ptr/struct.NonNull.html) instead of `*mut Node`. – Matthieu M. Jan 25 '19 at 09:55
  • @MatthieuM. Thanks for your comment, and in fact, I will try to use `NonNull` after I implement the basic logic, and also I removed the `if` check, it still crashes. – McGrady Jan 25 '19 at 10:00

1 Answers1

2

unsafe is a way of saying, "shut up, rustc, I know what I'm doing." In this case, you're assuring the compiler that v is always a valid aligned pointer to a Node<T>, that the array indexing of forward resolves to an array of Option<*mut Node<T>> with size MAX_HEIGHT. If any of these assumptions are violated, you're back in undefined behavior land.

You've turned off all the safeties and aimed your compiler at unknown pointers. The rational part of my brain wants to know exactly what you're trying to accomplish here.

The best advice I can offer with the information provided is to use rust-gdb and step through your program until your pointers don't look sane.

Jeff Hiner
  • 39
  • 1
  • 2