free causes exception

Igor via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 26 13:21:29 PST 2016


On Tuesday, 26 January 2016 at 19:34:22 UTC, Ali Çehreli wrote:
> On 01/26/2016 06:20 AM, Igor wrote:
> > I have successfully malloc'ed an object but when I go to free
> it in the
> > destructor I get an exception. The destructor simply has
> >
> > ~this() // destructor for Foo
> > {
> >      core.stdc.stdlib.free(&this);
> > }
>
> That design suggests a complexity regarding object 
> responsibilities: Assuming that the object was constructed on a 
> piece of memory that it did *not* allocate, the memory was 
> owned by somebody else. In that case and in general, freeing 
> the memory should be the responsibility of that other somebody 
> as well.
>
> Even if it is acceptable, you must also make sure that 
> opAssign() and post-blit do the right thing: no two object 
> should own the same piece of memory.
>
> Ali

That shouldn't be the case. I allocate in a static method called 
New once. I then deallocate in the destructor. Basically just as 
one would do in C++.

I'm not sure about opAssign and post-blit


class Foo
{
     ~this() // destructor for Foo
     {
		core.stdc.stdlib.free(cast(void *)this);
     }

         // Creates a Foo
	static public Foo New()
	{				
		auto buffer = 
core.stdc.stdlib.malloc(__traits(classInstanceSize, 
Foo))[0..__traits(classInstanceSize, Foo)];
		auto app = cast(Foo)emplace!Foo(buffer[]);
         }
}

hence

auto f = Foo.New();

then .destroy(f);

which is where the crash happens. If I don't destroy, it works 
fine + memory leak.

		


More information about the Digitalmars-d-learn mailing list