4

I was discussing doron's answer to this question, and it was said that

[one] will probably find that the C++ standard library defines new to use malloc under the hood.

I'm wondering if this is true. Does the C++ Standard define new to use malloc?

Community
  • 1
  • 1
Michael Dorst
  • 8,210
  • 11
  • 44
  • 71

4 Answers4

8

Does the C++ standard define new to use malloc?

The C++ Standard (meaning the Standard document that defines the C++ Language) doesn't define operator new in terms of malloc(). However, it is plausible that most implementations of the C++ Standard Library use malloc() to allocate memory.

Per Paragraph 18.6.1.1/4 of the C++11 Standard (about operator new):

Default behavior

  • Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether the attempt involves a call to the Standard C library function malloc is unspecified.
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • 1
    Relevant http://gcc.gnu.org/viewcvs/trunk/libstdc++-v3/libsupc++/new_opnt.cc?view=markup –  Mar 12 '13 at 19:35
2

Does the C++ standard define new to use malloc?

No, although many implementations do that for the default new implementation (it doesn't make much sense to provide separated heaps for malloc and new).

Also, the allocator function used by new is customizable (see §3.7.4.1), so it's particularly wrong to assume that new' will always callmalloc`, even on a given implementation.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

No, malloc just allocates memory. But new allocates memory and call constructors (if needs).

MAYBE in some part of implementation of new you find malloc-like mechanism as memory allocator.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • 2
    He asked if new uses malloc, not if they are the same thing. And obviously aren't since one is a function and one is a statement. – LtWorf Mar 12 '13 at 19:30
  • 1
    @LtWorf: that isn't strictly true. `new` is an operator, and `::operator new()` is just a function. – Michael Dorst Mar 12 '13 at 19:35
-1

I don't think so since malloc is not aware of constructors and you need a little extra than declaring a chunk of memory

Cratylus
  • 52,998
  • 69
  • 209
  • 339