I'm using an exe which dynamically loads a DLL. A function in the DLL allocates memory on the heap and passes a pointer to that memory to the exe.
A senior says that it is bad practice to do so. He says that if I ever have to share memory between the exe and the DLL, the exe has to allocate memory and pass a pointer to that to the DLL, and not vice versa. Is this true? Why?
EDIT: In my case, I planned to allocate and deallocate memory inside the DLL itself.
A function in the DLL allocates memory on the heap and passes a pointer to that memory to the exe.
Dynamic memory allocation is to allocate memory at “run time”. Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable). integer, 8, stored.
The problem with dynamic memory allocation is that it is not deallocated itself, developer responsibility to deallocate the allocated memory explicitly. If we cannot release the allocated memory, it can because of memory leak and make your machine slow.
Deallocation Of Allocated Memory With freeThe function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.
Here are some reasons for having the caller supply a pointer:
malloc
/free
while the .exe
is linked against a different version of malloc
/free
. (For example, the DLL could be using release versions while the .exe
is using specialized debug versions.)malloc
and instead wants memory to be allocated from some specific memory pool. Maybe it's a case where the caller could provide a pointer to memory allocated on the stack. If the DLL allocated the memory itself, the caller does not have any of these options.(The second and third points also mostly can be addressed by having the .exe
supply an allocator/deallocator for the DLL code to use.)
One of the basic idea behind the design patterns is ownership. The idea is - one who creates a resource (and thereby holds it in the pointer) should be responsible for deleting the resource
. This will ensure the sanctity of the design and in longer life of the projects, its developer can see lesser bugs.
So now it in your case, the DLL can be attached by any executable and he can try to delete the resource, which may cause future problem. So I think it has been suggested for vice-versa and I would say it as a sound advice.
I have seen this issue before, and it is caused by the DLL and exe linking differently to the CRT (static, dynamic MT etc).
I you're going to pass a pointer to memory between DLL and executable, they should both provide some sort of Free()
functionality to free memory from their respective heaps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With