c++: new, delete, malloc, free的匹配使用
2016-07-22 15:46
621 查看
cplusplus: new, delete, malloc, free的匹配使用
今天师姐项目调试时遇到问题, 跑来问我:为什么用new申请的内存, 用free释放有时候没问题, 有时候又有问题呢?
在C++中, 我们可以用new和malloc申请空间, 用delete和free释放空间。
malloc和free只对内存块进行操作, 而new和delete除了对内存块进行操作,
还会调用构造/析构函数(如果是类空间)。
而类里的成员变量, 可能是指针或句柄, 其实际指向的资源, 并不在类的内存块中。
这时贸然使用free释放, 就会产生内存泄露。
当然, 如果内存块中存储的是基本数据类型, 使用delete和free都不会有内存泄露。
只是这样的写法并不规范。
规范的写法是:
new与delete, new[]与delete[], malloc和free对应使用。
示例代码
使用VLD检测内存泄露,情况3存在内存泄漏#include <cstdlib> #include <iostream> #include <vld.h> #pragma comment(lib, "vld.lib") class Hand { public: void* handle; Hand() : handle(nullptr) {} ~Hand() { if (handle != nullptr) free(handle); } void memory() { if (handle == nullptr) handle = malloc(100); } }; int main() { // condition 1: malloc and free { Hand* handle = reinterpret_cast<Hand*>(malloc(sizeof(Hand))); free(handle); } // condition 2: new and free (without memory) { Hand* handle = new Hand(); free(handle); } // condition 3: new and free (with memory allocation) { Hand* handle = new Hand(); handle->memory(); free(handle); } }
参考链接
new: http://www.cplusplus.com/reference/new/operator%20new/delete: http://www.cplusplus.com/reference/new/operator%20delete/
free: http://www.cplusplus.com/reference/cstdlib/free/
相关文章推荐
- mysql Out of memory (Needed 16777224 bytes)的错误解决
- MySQL Memory 存储引擎浅析
- PHP错误Allowed memory size of 67108864 bytes exhausted的3种解决办法
- Git使用小坑 Out of memory错误的解决方法
- mysqld-nt: Out of memory (Needed 1677720 bytes)解决方法
- linux系统调优-Cgroups
- 利用系统缓存提高PostgreSQL操作效率
- MySQL 的三大引擎:InnoDB、MyISAM和Memory
- SQL Server内存架构基础
- SQL Server内存故障排除
- SQL Server 2012内存
- 如何理解VMware内存资源管理
- VMware vSphere内存管理机制解析 — 内存回收
- Using Memory Efficiently(Pro Android Apps Performance Optimization)
- ORA-04031问题
- System and device programming——kernel Buffer
- System and device programming-Memory management in Windows
- 为什么用GPU挖比特币?
- 10种启动故障解决方法
- 怎样在xcode里面使用Memory Leaks和Instruments教程