new,delete,malloc&自由 [英] new, delete ,malloc & free

查看:134
本文介绍了new,delete,malloc&自由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题在面试中向我问过:

This question was asked to me in an interview:


在C ++中,

In C++,


  1. 如果我们使用 malloc 分配内存并使用 delete 内存?

  2. 如果我们使用 new 分配内存, c>

  1. what if we allocate memory using malloc and use delete to free that allocated memory?
  2. what if we allocate the memory using new and free it using free?

如果在代码中使用上述内容,我们会遇到什么问题?

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?

推荐答案

如果你这样做,你会遇到未定义的行为。永远不要试试。虽然 new 可能通过 malloc() delete 可以通过 free()实现,不能保证它们是真正实现的,用户也可以重载 new 删除

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.

除此之外不要忘记当你调用 malloc()得到原始内存 - 没有构造函数被调用 - 当你调用 free()没有析构函数被调用。这可能导致程序的未定义行为和不正常的功能。

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.

这篇关于new,delete,malloc&自由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆