What does "new" use when a runtime library is not used?
In C for example, there is no ma开发者_如何学Pythonlloc() without a runtime library (libc). And I think for example, on Windows malloc just calls HeapAlloc(). But in C++, the way to allocate dynamic memory is actually a keyword of the language; same for "delete". So therefore, how would "new" work if you compiled your code without a runtime library?
Thanks
If new operator is not overloaded, it is generally the same as malloc function. It is platform dependent. The only difference, is that it automatically manage the initialization of the data.
EDIT:
On linux you can not compile without standard library. You got the following message:
phong@colinux ~ $ g++ -nostdlib test.cpp
/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 00000000080480d8
/tmp/ccOV36hW.o: In function `main':
test.cpp:(.text+0x11): undefined reference to `operator new(unsigned int)'
test.cpp:(.text+0x21): undefined reference to `operator delete(void*)'
/tmp/ccOV36hW.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
Like any function pointer not found.
Dynamic memory allocation (as is also printf()
) requires OS support. You cannot write a hardware (or OS) independent versions of these functions.
A program without any OS support (as you expect from C) won't be able to interact with the outside, so it's useless.
This means that this pure theoretical question has no sense.
@In silico: This is a hard one.. On a controller, you have to know some details about the particular hardware you run, so that you know that *(char*)(0x123)^=1
will toggle a led. It's not something defined in C standard, but your knowledge about outside. The OS is nothing else than a collection of knowledge about the hardware.
Sure, you could run without CRT (as some viruses do), by finding the kernel address in memory and looking for exported functions. But again, it just reproduce the function of CRT that is simly vital to any program.
@Fred Nurk: What I wanted to say is that "pure C" does not define any standard mean to interact with the hardware, it is something done by OS. So there is no point of running such program. For example, you could not write a "generic" malloc
that would run on every system.
@Phong: yes, and this would mean that you've just written the CRT (or OS) for it. And it won't be portable as is the "pure C" itself.
NOTE: by OS support I also mean the knowledge about the particular hardware
By pure C I mean portable code that uses only standard C constructs.
精彩评论