Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
MichaPau opened this issue Oct 19, 2024 · 0 comments
Open

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

MichaPau opened this issue Oct 19, 2024 · 0 comments

Comments

@MichaPau
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant