• Advertisement
Sign in to follow this  

malloc/free across modules

This topic is 2690 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi there.

I have heard that the memory you allocate with 'new' you shoud delete in the same module it was allocated in(do not know why).

I wonder wheather this aply only for new/delete, or for malloc/free as well.

Share this post


Link to post
Share on other sites
Advertisement
There is no language reason why allocation and release should be in the same module. It might just be a general rule to help you keep things under control and avoid memory leaks, but it's not a requirement.

Share this post


Link to post
Share on other sites
Memory allocated by a particular C/C++ runtime should be deallocated by the same runtime, because different runtimes may use separate or incompatible allocation structures. This is not an issue if the two modules use the same runtime library version and link to it dynamically, which is the most common situation if you aren't dealing with third-party plugins and haven't changed any default subsystem settings. But yes, this is an issue with both new/delete and malloc/free.

Share this post


Link to post
Share on other sites
I think the question here is, "what do you mean by module?"

If, by module, you mean a particular class or group of function, the the 1st response is what your looking for.

If, by module, you mean different libraries or plugins, then the 2nd response is what you're looking for.

Share this post


Link to post
Share on other sites
Quote:
Original post by JohnnyCode
I wonder wheather this aply only for new/delete, or for malloc/free as well.


All of these may be redefined. In practice, they will be a regular function that performs some syscall to obtain memory. Redefinition can also occur indirectly, due to linking or other obscurities. Often it will be a bug, an undesirable side-effect of linking but sometimes it'll be intentional or required.

All that matters is that correct pairs are used. Same new and delete and same malloc and free.

What same means is rather vague, but different versions of new could use different memory pools. So allocating from pool A and freeing into pool B is obviously an error. In OO terms, new/free would be member functions, and same instance would need to be used.

This is a fairly big deal when integrating third-party libraries. Same type of issues occurs when passing STL allocators across DLL boundaries.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement