C语言-内存管理


常量区(军事管理区,不可以修改)

特点
  1. 整型常量 10 20 -10
  2. 浮点常量 1.2 1.001
  3. 字符常量 'a' '0' '\0'
  4. 字符串常量 "asdf" "123"
  5. 地址常量 int a; &a 数组名 函数名

栈区

特点
  1. 租的房子,房子到期自动回收
  2. 访问速度快
  3. 空间少
  4. 作用域和生命周期从定义的位置开始 '}'
  • 局部变量
  • 函数变量

全局区(全局变量)

特点
  1. 局部大于全局
  2. 初始化默认为0
  • 生命周期 程序开始到程序结束
  • 作用域:整个项目
引用其他文件中的全局变量
/*main.c*/
#include
int g_value;

int main(){
    printf("%d",g_value);
    return 0;
}

/*a.c*/
extern int g_value; //extern 引用其他文件的全局变量
void print(){
    g_value = 200;
}

静态区

静态局部变量
  • 生命周期:从程序开始到程序结束
  • 作用域:到 '}'结束
  • 只被初始化一次
#include
void fun(){
    int a = 10;
    static int s = 10;
    printf("%d",a++);
    printf("%d",s++);
}

int main(){
    fun();  //10 10
    fun();  //10 11
    return 0;
}
静态全局变量
  • 生命周期:程序开始到程序结束
  • 作用域 :当前文件
  • 特点:不怕重名

堆区

特点
  1. 不会自动释放
  2. 容量大
  3. 访问速度慢
  4. 堆区空间没名字
注意
  1. 不要访问越界
  2. 不要忘记释放空间
#include
#include
#include
int main(){
    char* p =malloc(400);//在堆区申请空间
    strcpy(p,"12345");
    //房子不用的时候记得释放
    free(p);
    return 0;
}

GetMemory的几个面试题

Test1
void GetMemory1(char *p){
    p = (char *)malloc(100);
    
}
void Test1(void){
    char *str = NULL;
    GetMemory1(str);
    strcpy(str,"hello world");
    printf(str);
}
//输出结果:访问空指针,异常退出

solution1

#include
#include
#include
char* GetMemory1(char *p)
{
    p = (char *)malloc(100);
    return p;
}
void Test1()
{
    char *str = NULL;
    str = GetMemory1(str);
    strcpy(str,"hello world");
    printf(str);
    free(str);
}
int main()
{
    Test1();
    return 0;
}

solution2

ti3pgnokzfvd29aerc_xnw

#include
#include
#include
char* GetMemory1(char **p)
{
    *p = (char *)malloc(100);
}
void Test1()
{
    char *str = NULL;
    str = GetMemory1(&str);
    strcpy(str,"hello world");
    printf(str);
    free(str);
}
int main()
{
    Test1();
    return 0;
}
Test2
char *GetMemory2(void){
    char p[] = "hello world";
    return p;
    
}
void Test2(void){
    char *str = NULL;
    str = GetMemory2();
    printf(str);
}
//输出结果:字符串数组在栈区分配,函数结束被释放,输出乱码
Test3
char *GetMemory3(void){
    char *p = "hello world";
    return p;
    
}
void Test3(void){
    char *str = NULL;
    str = GetMemory3();
    printf(str);
}
//输出结果:hello world
Test4
char *GetMemory4(void){
    static char p[] = "hello world";
    return p;
    
}
void Test4(void){
    char *str = NULL;
    str = GetMemory4();
    printf(str);
}
//输出结果:hello world 静态局部变量不会被释放空间,生命周期是全局的
Test5
void Test5(void){
    char *str = (char *)malloc(100);
    strcpy(str,"hello");
    free(str);
    //str = NULL;
    if(str!=NULL){
        strcpy(str,"world");
        printf(str);
    }
}
//输出结果:world 内存已经被释放,访问野指针造成内存泄漏
Test6
void Test6(){
    char *str = (char *)malloc(100);
    strcpy(str,"hello");
    str+=6;
    free(str);
    //str = NULL;
    if(str!=NULL){
        strcpy(str,"world");
        printf(str);
    }
}
//输出结果:出现异常,释放空间不对