Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Is `operator new` Implemented At The Linker Level?

Per the C++ documentation, the operator new/etc. functions are:

implicitly declared in each translation unit[, and t]he program is ill-formed [...] if more than one replacement is provided in the program for any of the replaceable allocation function[s]".

That is, if the programmer does not define their own operator new, then the C++ standard library must provide it. Conversely, if they do provide it, then the standard library mustn't.

I understand this behavior, but what I don't understand is how this works at a linker level.

The C++ standard library is compiled before the program that uses it, which is where the programmer is deciding whether to define their own operator new. Thus, the C++ standard library does need to speculatively provide an operator new somewhere. But then, when the user's program is linked against the standard library, if they did define their own allocation function, then that would result in multiple definitions and run afoul of the documentation above (in practice, you get a linker error about duplicate symbols, thank goodness).

Conversely, if the standard library doesn't define the operator new, then of course the user would have to do so, or else any call to it will result in missing symbols (and so a linker error the other way).

like image 223
imallett Avatar asked Dec 12 '25 00:12

imallett


1 Answers

At least for ELF format, you can define symbols as weak using __attribute__((weak)).

If there are both weak and a normal symbols during linking, the normal symbol takes priority. So weak symbols can act as defaults or fallbacks.

The standard library can define operator new as weak, giving the userspace application an opportunity to override it but if it does not, the library's weak symbol is used, thus avoiding both the undefined reference and multiple definitions errors.

The same mechanism works with system calls usually, quite handy for mocking during unit tests.

like image 157
Quimby Avatar answered Dec 13 '25 14:12

Quimby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!