1.C/C++内存分布
int globalVar = 1;
static int staticGlobalVal = 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);
}
以下变量在哪个区?
A.栈 B.堆 C.数据段(静态区) D.代码段(常量区)
globalVar | C |
staticGlobalVal | C |
staticVar | C |
localVar | A |
num1 | A |
char2 | A |
*char2 | A |
pChar3 | A |
*pChar3 | D |
ptr1和*ptr1 | A/B |
abcd\0在常量区,再把常量区的abcd\0复制给char2,char2 数组在栈上,数组名就是首元素的地址,所以char2在栈上,pChar3是指针,存的是常量区中abcd\0的地址,所以解引用就是指向常量区。ptr1在栈上面,开的空间在堆上面。
sizeof(num1)=40 | sizeof(char2)=5 |
strlen(char2)=4 | sizeof(pChar3)=4/8是一个指针,32/48 |
strlen(pChar3)=4 | sizeof(ptr1)=4/8 |
2.内存泄漏
长期运行的程序,比如服务器/有些应用 QQ,影响很大,出现内存泄漏会导致响应越来越慢,最终卡死。