Does dynamic memory allocation differ in C and C++ in popular implementations?

Here is the implementation used by g++ 4.6.1:

_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) throw (std::bad_alloc)
{
  void *p;

  /* malloc (0) is unpredictable; avoid it.  */
  if (sz == 0)
    sz = 1;
  p = (void *) malloc (sz);
  while (p == 0)
    {
      new_handler handler = __new_handler;
      if (! handler)
#ifdef __EXCEPTIONS
        throw bad_alloc();
#else
        std::abort();
#endif
      handler ();
      p = (void *) malloc (sz);
    }

  return p;
}

This is found in libstdc++-v3/libsupc++/new_op.cc inside the g++ source distro.

As you can see, it’s a fairly thin wrapper around malloc.

edit On many systems it is possible to fine-tune the behaviour of malloc, typically by calling mallopt or setting environment variables. Here is one article discussing some features available on Linux.

According to Wikipedia, glibc versions 2.3+ use a modified version of the allocator called ptmalloc, which itself is a derivative of dlmalloc designed by Doug Lea. Interestingly, in an article about dlmalloc Doug Lea gives the following perspective (emphasis mine):

I wrote the first version of the allocator after writing some C++
programs that almost exclusively relied on allocating dynamic memory.
I found that they ran much more slowly and/or with much more total
memory consumption than I expected them to. This was due to
characteristics of the memory allocators on the systems I was running
on (mainly the then-current versions of SunOs and BSD ). To counter
this, at first I wrote a number of special-purpose allocators in C++,
normally by overloading operator new for various classes. Some of
these are described in a paper on C++ allocation techniques that was
adapted into the 1989 C++ Report article Some storage allocation
techniques for container classes.

However, I soon realized that building a special allocator for each
new class that tended to be dynamically allocated and heavily used was
not a good strategy when building kinds of general-purpose programming
support classes I was writing at the time. (From 1986 to 1991, I was
the the primary author of libg++ , the GNU C++ library.) A broader
solution was needed — to write an allocator that was good enough
under normal C++ and C loads
so that programmers would not be tempted
to write special-purpose allocators except under very special
conditions.

This article presents a description of some of the main design goals,
algorithms, and implementation considerations for this allocator.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)