C++动态内存管理
一、引言
一道题目复习知识点
int globalVar = 1;
static int staticGlobalVar = 1;
void Test()
{
static int staticVar = 1;
int localVar = 1;
int num1[10] = {1, 2, 3, 4};
char char2[] = "abcd";
char* pChar3 = "abcd";
int* ptr1 = (int*)malloc(sizeof (int)*4);
int* ptr2 = (int*)calloc(4, sizeof(int));
int* ptr3 = (int*)realloc(ptr2, sizeof(int)*4);
free (ptr1);
free (ptr3);
}
- 选项: A.栈 B.堆 C.数据段(静态区) D.代码段(常量区)
- globalVar在哪里? C
- staticGlobalVar在哪里? C
- staticVar在哪里? C
- localVar在哪里? A
- num1 在哪里? A
- char2在哪里? A
- *char2在哪里? A
- pChar3在哪里? A
- *pChar3在哪里? D
- ptr1在哪里? A
- *ptr1在哪里? B
- sizeof(num1) =40
- sizeof(char2) =5
- strlen(char2) = 4
- sizeof(pChar3) = 4
- strlen(pChar3) =4
- sizeof(ptr1) = 4
由于c语言中动态申请太麻烦所以C++引入新的
二、new
1. 与malloc比较
c语言动态开辟太麻烦
引入new
int main()
{
int* a = (int*)malloc(sizeof(int) * 4);
int* b = new int(5);
int* c = new int[4];
free(a);
delete b;
delete[] c;
return 0;
}
- 在内置类型上基本没有区别
- C++98不支持初始化数组,C++11可以支持初始化数组,类似b那样的初始化c
- new对象的时候会调用类的构造函数,delete时候会调用析构函数
2. 动态内存开辟失败
int main()
{
char* p1 = (char*)malloc(1024u*1024u*1024u*2u);
if (p1 == nullptr)
{
printf("%d\n", errno);
perror("malloc fail");
exit(-1);
}
else
{
printf("%p\n", p1);
}
return 0;
}
这里是抛异常捕获的方法,catch只会捕获try内的东西
int main()
{
try
{
double* p1 = new double[1024u * 1024u * 1024u];
printf("%p\n", p1);
}
catch (const exception& e)
{
cout << e.what() << endl;
}
return 0;
}
|