Is it safe for me to manage dll class memory if I call new and delete?

If my DLL has an implementation of one of my classes, if I do a new one and delete, is this normal? When there is a problem with DLL and who allocates what?

What if this class calls a new one?

    class InDLL {
    A* something;

    InDLL()
    {
       something = new A;
    }
    };

    ...

    //me

InDLL dll = new InDLL(); //problem?

thank

+3
source share
2 answers

An important rule is that the one who allocates the memory is responsible for freeing that memory using the same allocator . There is no restriction on how memory should be allocated (it can be assigned as the main executable file, your DLL or some other DLL), but after allocating it, the same module should free it.

, , - DLL , . , . :

// In mydll.dll:
class MyClass { ... };

MyClass * DLLEXPORT NewMyClass()
{
    return new MyClass;
}

void DLLEXPORT FreeMyClass(MyClass *obj)
{
    delete obj;
}

, , (, NewMyClass() ) (, ):

// THIS CODE IS BUGGY, DO NOT USE:
HMODULE mydll = LoadLibrary("mydll.dll");
MyClass (*NewMyClass)() = (MyClass (*)())GetProcAddress(mydll, "NewMyClass");
MyClass *obj = NewMyClass();  // allocate inside DLL
...
delete obj;  // BOOM!

, ( ) , C/++. , , , malloc/free operator new/operator delete .

. .

+6

, , . , new, DLL, new, .

0

Source: https://habr.com/ru/post/1782390/


All Articles