1

The articles explaining the internals of malloc and free in glibc are abundant in number. However, I'd like to know how dynamic memory management works in C++, specifically the nitty gritty of new and delete operators. My interest is in the internal data structure maintained as well as the allocation and de-allocation algorithms. What are a few good resources for the same?

8

This is somewhat compiler-specific but in most cases new and delete are basically thin wrappers around malloc and free (regarding the allocation of memory itself). Some additional C++ specifics regarding new expressions and the sequence of construction/destructions of classes and their members are described in the C++ standard (a nice summary is available at cppreference). I have described some of the details pertaining to the MSVC++ implementation here

A few additional wrinkles:

  • a class can redefine a custom operator new/delete which will be called instead of the global one when constructing instances of that class. This can lead to tricky situations with polymorphic classes so the compiler may need to introduce a hidden virtual destructor function (see again my OpenRCE article).

  • when allocating an array of classes, many compilers also embed a number of elements in the memory allocated for the array so that it can be destructed correctly. This is one of the reasons why mixing delete and delete[] can be dangerous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.