1. malloc/free与new/delete的区别
- 1、malloc/free是C语言的标准库函数;new/delete是C++的运算符;
- 2、对于非内部数据类型的对象而言,malloc/free无法满足动态对象的要求;对象在创建的同时要执行构造函数,对象消亡之前执行析构函数;由于malloc/free是库函数而不是运算符,不在编译器的控制权限之内。
2. malloc/free的使用
void malloc(size_t size);
int *p = (int *)malloc(sizeof(int) * length);
int free(void *Pointer);
malloc和free必须一块使用,在调用malloc函数的时候,也要调用free函数;此外,free函数不能对同一个指针释放两次甚至更多,否则将会造成内存泄漏。
#define MAX_NUM_SIZE 128
void malloc_free()
{
char *p = NULL;
*p = (char*)malloc(sizeof(char) * MAX_NUM_SIZE);
if(NULL == p)
{
printf("malloc error\n");
exit(1);
}
else
{
printf("malloc successful\n");
}
return;
}
3. new/free的使用
int *p1 = new int;
int *p2 = new int[length]; // new有内置sizeof、类型转换、类型安全检测
delete []p2; // 释放数组
delete p1; // 释放变量
4. 内存耗尽
定义:C++在申请动态内存时,找不到足够大的空间。
- 在malloc或者new内存时,判断是否申请内存成功;如果不成功,return结束函数的运行。
int m_malloc(int Length)
{
int *p = (int*)malloc(sizeof(int) * Length);
if (NULL == p)
{
cout << "malloc error" << endl;
return 0;
}
return Length;
}
- 在malloc或者new内存时,判断是否申请内存成功;如果不成功,exit(1)结束程序的运行。
int m_malloc(int Length)
{
int *p = (int*)malloc(sizeof(int) * Length);
if (NULL == p)
{
cout << "malloc error" << endl;
exit(1);
}
return Length;
}
- 设置malloc和new的异常处理函数。