new, delete ,malloc & free

后端 未结 2 1057
面向向阳花
面向向阳花 2020-12-05 15:41

This question was asked to me in an interview:

In C++,

  1. what if we allocate memory using malloc and use delete<
2条回答
  •  眼角桃花
    2020-12-05 16:03

    If you do so you will run into undefined behavior. Never try that. Although new might be implemented through malloc() and delete might be implemented through free() there's no guarantee that they are really implemented that way and also the user can overload new and delete at 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 call free() 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.

提交回复
热议问题