This question was asked to me in an interview:
In C++,
- what if we allocate memory using
mallocand usedeleteto free that allocated memory?- what if we allocate the memory using
newand free it usingfree?What are the problems that we would face if the above things are used in the code?
My answer was there is no difference. Was I right in saying so?
If you do so you will run into undefined behavior. Never try that. Although
newmight be implemented throughmalloc()anddeletemight be implemented throughfree()there’s no guarantee that they are really implemented that way and also the user can overloadnewanddeleteat his discretion. You risk running into heap corruption.Other than that don’t forget that when you call
malloc()you get raw memory – no constructor is invoked – and when you callfree()no destructor is invoked. This can as well lead to undefined behavior and improper functioning of the program.The bottom line is… never do this.