new, delete ,malloc amp; free(新建,删除,malloc amp;自由)
问题描述
这个问题是在一次采访中问我的:
This question was asked to me in an interview:
在 C++ 中,
- 如果我们使用
malloc分配内存并使用delete来释放分配的内存会怎样? - 如果我们使用
new分配内存并使用free释放它会怎样?
- 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?
推荐答案
如果你这样做,你会遇到未定义的行为.永远不要尝试.尽管 new 可能通过 malloc() 实现,而 delete 可能通过 free() 实现,但不能保证它们确实是这样实现的并且用户也可以自行决定重载new和delete.您可能会遇到堆损坏.
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.
这篇关于新建,删除,malloc &自由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:新建,删除,malloc &自由
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
