If I'm writing 100% ANSI C but compiling in .cpp files will the compiler automatically "optimize" malloc and free calls to new and delete? Does that even make sense given their differences? I didn't think this is how it worked but a friend of mine said this is what happens.
3 Answers
C++ is very specific in c.malloc:
The functions
calloc(),malloc(), andrealloc()do not attempt to allocate storage by calling::operator new().The function
free()does not attempt to deallocate storage by calling::operator delete().
18 Comments
malloc() is not commonly one of them, but I know of no reason that it couldn't be.printf where the argument is a string with no format specifiers that ends in \n is often optimized by replacing it with puts, but that also has external linkage, does it not?There's a bit of an ambiguity in the question.
int *ip1 = malloc(sizeof int); int *ip2 = new int; Those two in fact do the same thing: create an uninitialized value on the heap and assign its address to the pointer on the left-hand side.
But:
struct S { /* whatever */ }; S *sp1 = malloc(sizeof S); S *sp2 = new S; Those two don't necessarily do the same thing. If S has a constructor, new S will allocate memory and call the constructor; malloc(sizeof S) will only allocate memory.
I mentioned an ambiguity. There's another possible meaning for "replace new, and that is using calls to operator new:
struct S { /* whatever */ }; S *sp1 = malloc(sizeof S); S *sp2 = ::operator new(sizeof S); On the surface, by default these two do the same thing: they allocate memory on the heap for an object of type S and return a pointer to that memory; neither one initializes the object. But there's an important difference. If malloc can't allocate memory it returns a null pointer. If operator new can't allocate memory it throws an exception of type std::bad_alloc (there's more to it than that, but that's enough difference for now).
That's also true for new S: it throws an exception if it can't allocate memory, while malloc returns a null pointer.
Comments
Do C++ compilers generally “optimize” malloc and free to new and delete?
No.
Optimizing is an act that reduces the workload of your program.
Since new and delete invoke constructors and destructors respectively, while malloc() and free() do not, it makes no sense to optimize them.
Usually new will call malloc(), which also adds to my point above, as mentioned in Does ::operator new(size_t) use malloc()?
PS: "I'm writing 100% ANSI C" is not going to make a C++ compiler happy in any way...
mallocdoesn't invoke constructors, whilenewdoes. Hence, "optimizing" something to do more work - doesn't make sense.mallocis legal to call in C++ and sometimes is actually what you need to do.newanddeleteare implemented in terms ofmallocandfree.int main(int argc, char **argv) { if (argc == 0) return 0; else return main(0, 0); }newanddeleteend up callingmallocandfreeat some point.