Skip to content

ch 6.3.3 eprintln! macro in alloc produces endless alloc loop #119

@MichaPau

Description

@MichaPau

Running the graphical application to create and destroy objects on the heap (Listing 6.9)
creates an endless loop. (ManjaroLinux release: 24.1.1; rustc 1.81.0).

and stops with the error : 'cargo run' terminated by signal SIGSEGV (Address boundary error)

this happens when using a macro like eprintln! or format! etc.
println! makes the application hang.

With the help from https://users.rust-lang.org (link below) I found a workaround using extern "C" printf:

extern "C" {
    fn printf(format: *const c_char, ...) -> c_int;
}
struct MyAllocator;


unsafe impl GlobalAlloc for MyAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        
        let start = Instant::now();
        let ptr = System.alloc(layout);
        let end = Instant::now();
        let ellapsed = end - start;
        let ellapsed_value = ellapsed.as_nanos();
        let v = layout.size();
        
        //eprint!("{}\t{}", v, ellapsed_value);
        let format: *const c_char = c"%d\t%d \n".as_ptr().cast();
        let _ = printf(format, v, ellapsed_value);

        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        System.dealloc(ptr, layout)
    }
}

This works on my system. I don't know if it's still possible that it allocates on the heap for others.

Link to the issue on rust-org

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions