7

See linked question.

Difference between global operator new and malloc

The accepted answer states,

"Replacing malloc opens up a can of worms. It can be done, but not portably, because it requires knowledge of the linker."

Why does replacing malloc require knowledge of the linker and why does replacing ::operator new() not?

Community
  • 1
  • 1
Praxeolitic
  • 22,455
  • 16
  • 75
  • 126
  • The same reason you can forward declare if you just have a pointer, but need a full include if you have an instance of an object. http://stackoverflow.com/questions/553682/when-can-i-use-a-forward-declaration?rq=1 – Cory Kramer Jul 01 '14 at 19:13
  • The statement from the linked answer says `3. new has the concept of a new_handler, for which there is no malloc equivalent.` . IMHO that's not 100% true. There are usually several weak symbols declared in the underyling c library, that can be _overridden_ with your own implementations (see e.g. [`_sbrk`](http://en.wikipedia.org/wiki/Sbrk)). Declared weak symbols doesn't necessarily involve _Knowdlege of the linker_. – πάντα ῥεῖ Jul 01 '14 at 19:14

1 Answers1

7

Standard C++ makes provisions for overriding ::operator new. While the implementation is certainly messy and linker-related, a C++ program can just define a different ::operator new and it works. The C++ standard explicitly says: Programs can replace these with their own definitions (etc. etc. various restrictions and details).

malloc on the other hand is an ordinary function defined in an ordinary library, and C (and C++, for that matter) has no facilities for replacing a function like that. You can convince virtually every linker under the sun to link to your libc sans malloc and resolve references to malloc to some code from another library/object file. But you can't just define a different malloc functions since that violates the one-definition rule: You end up with two functions called "malloc" in the program, which is both prohibited by the standard (for non-static, non-anonymous-namespace, non-inline, ... functions) and a serious problem for linkers (most likely, an error or one of the two definitions is dropped).