rust-cpp icon indicating copy to clipboard operation
rust-cpp copied to clipboard

class on free aborts on invalid pointer

Open andyjsbell opened this issue 3 years ago • 5 comments

Using the cpp_class! macro with a simple class aborts on freeing the resource. This is happening on Ubuntu 1804. Code snippet reproducing the issue:

use cpp::cpp;
use cpp::cpp_class;

cpp!{{
    #include <iostream>
    
    using std::string;

    class Test {
    public:
        Test() {
            std::cout << "creating" << std::endl;
        }
        virtual ~Test() {
            std::cout << "destroying" << std::endl;
        }

    protected:
        std::string message; // -> removing this and we don't get the issue
    };
}}

cpp_class!(pub unsafe struct Test as "Test");
impl Test {
    fn new() -> Self {
        unsafe { cpp!([] -> Test as "Test" { return Test(); }) }
    }
}

fn main() {
    let test = Test::new();
}

andyjsbell avatar Jul 16 '20 11:07 andyjsbell

Yeah, cpp_class only work with class that are relocatable.

This is documented there: https://docs.rs/cpp/0.5.5/cpp/macro.cpp_class.html#relocatable-classes

Perhaps the documentation should be more explicit, or extra warning should be in order.

ogoffart avatar Jul 16 '20 14:07 ogoffart

I decided to test this out on OSX and Windows. Interestingly both Windows and OSX did not have the issue.

andyjsbell avatar Jul 24 '20 16:07 andyjsbell

This depends on the implementation of the standard library.

ogoffart avatar Jul 24 '20 17:07 ogoffart

Hi, out of curiosity, why test is relocatable immediately ? it is used only once.

LastLightSith avatar Nov 22 '21 08:11 LastLightSith

Internally it is returned from the Test::new() function so that's one possible relocation (even if it might be optimized) Also internally in the cpp! macro

ogoffart avatar Nov 22 '21 09:11 ogoffart