gpt4 book ai didi

c++ - 新建、删除、malloc 和免费

转载 作者:IT老高 更新时间:2023-10-28 22:59:34 26 4
gpt4 key购买 nike

在一次采访中问我这个问题:

In 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?

我的回答是没有区别。我说的对吗?

最佳答案

如果这样做,您将遇到未定义的行为。永远不要那样做。虽然 new 可能通过 malloc() 实现,而 delete 可能通过 free() 实现,但不能保证它们实际上是以这种方式实现的并且用户也可以自行决定重载newdelete。您可能会遇到堆损坏。

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

底线是......永远不要这样做。

关于c++ - 新建、删除、malloc 和免费,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3184118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com