Skip to content

segmentation fault: moved value not detected due to trait usage #14061

Closed
@dhardy

Description

@dhardy

With a little bit of hacking, I found a memory safety violation:

// This causes a seg-fault.

struct S<T> { val : T }
trait Gettable<T>{
    fn get(&self) -> T;
}
impl<T : Copy> Gettable<T> for S<T> {
    // Note: ~str does not satisfy Copy yet this compiles
    fn get(&self) -> T { self.val }
}

fn main() {
    let t : Box<S<~str>> = box S { val: "one".to_owned() };
    let a = t as Box<Gettable<~str>>;
    let b = a.get();    // causes a move
    //Note: without use of a trait, doing this results in:
    //error: instantiating a type parameter with an incompatible type `~str`, which does not fulfill `Pod`

    println!( "a: {}", a.get() );       // another move, crash ensues
    println!( "b: {}", b );
}

Note: what's the best way to "get" a value via a trait? Copy and restrict to POD types? Reference, even if most of the values accessed are just ints? Or use clone − and risk issues on complex types?

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-crashIssue: The compiler crashes (SIGSEGV, SIGABRT, etc). Use I-ICE instead when the compiler panics.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions