New Operator

Can use mix up new operator and free().if not why? And please give internal details when new,delete,malloc,free are called
You shouldn't mix new and free because you are not granted that they use the same way to allocate memory ( and free does not call constructors )

new/new[]: allocate memory and call constructors for the allocate objects
delete/delete[]: call the destructors for the objects and frees memory
malloc: allocate a bunch of bytes
free: frees memory allocated with malloc

The way memory is allocated will depend on the system and compiler but a rough approximation is:

Allocation:
- check whether there's enough contiguous memory for the program to allocate something of the required size
- if not, ask to the OS for some more memory ( the available addresses would be store in some kind of structure )
- if you have enough memory remove it from the structure which keeps track of the available memory

Deallocation:
- merge the memory back into the structure
But in both the cases memory is allocated using new/malloc either contor is called or not so what is the problem logically/technically if we mix new with free?
free() may use a different memory mapping. For example 0xA in free's map might be 0xF000 in actual memory where as new's 0xA might be 0xE000 in actual memory.
That means only difference is memory mapping if same memory mapping is there we can mix new and free right!!
Last edited on
The main problem with free and C++ is that free does not call destructors.
Also, near the allocated memory you may find some extra information ( like the size of the allocated memory for the object ) and those may be different for stuff allocated by new or malloc.
Why do you want to mix them anyway?
That means only difference is memory mapping if same memory mapping is there we can mix new and free right!!


No. Don't mix them. Ever.

There's no reason to.
I agree, it leads to disastrous results. Tried it and it didn't work. Use new/delete for classes.
@Bazzy : But what is the problem if free does not call destructor.Ultimate goal is to free allocated memory.I think new allocated memory for that object from heap and free can deallocate that.I nderstand I should not mix them but why is still not clear......
If you allocate an object of std::string for example, it will allocate some other memory for its internal buffer.
Once you free the string object without calling its destructor, the internal buffer will still be in memory resulting in a leak.
Topic archived. No new replies allowed.