目录
4. operator new与operator delete函数
4.1 operator new与operator delete函数(重点)
1. C/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";
const 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);
}
1. 选择题:
选项: 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__
2. 填空题:(x64环境下)
sizeof(num1) = __40__;
sizeof(char2) = __5__; strlen(char2) = __4__;
sizeof(pChar3) = __8__; strlen(pChar3) = __4__;
sizeof(ptr1) = __8__;
3. sizeof 和 strlen 区别?
1:sizeof:计算所占空间字节的大小(包括‘\0’)。
2:strlen:计算字符串长度,遇到‘\0’停止。
【说明】
1. 栈又叫堆栈--非静态局部变量/函数参数/返回值等等,栈是向下增长的。
2. 内存映射段是高效的I/O映射方式,用于装载一个共享的动态内存库。用户可使用系统接口
创建共享共享内存,做进程间通信。
3. 堆用于程序运行时动态内存分配,堆是可以上增长的。
4. 数据段--存储全局数据和静态数据。
5. 代码段--可执行的代码/只读常量。
2. C语言中动态内存管理方式
【面试题】
1. malloc/calloc/realloc的区别?
(1)malloc:
(2) calloc:
(3) realloc:
简单来说:realloc分为异地调整和原地调整。
2. malloc的实现原理?