C++内存学习笔记

C++内存学习笔记

1. 内存分区模型

1.1 程序运行前

不在全局中的数据

复制代码
1. 局部变量
2. const 修饰的局部变量

全局区

复制代码
1. 全局变量
2. 静态变量
3. 常量
	字符串常量
	const修饰的全局变量(全局常量)
4.该区域的的数据在程序结束后由操作系统释放
cpp 复制代码
#include <iostream>
using namespace std;

// 全局变量
int g_a = 10;
int g_b = 10;

// 全局常量
const int c_g_a = 10;

int main(int argc, char const *argv[])
{

    // 局部变量
    int a = 10;
    int b = 10;
    cout << "局部变量a的地址为:\t" << &a << endl;
    cout << "局部变量b的地址为:\t" << &b << endl;

    cout << "全局变量g_a的地址为:\t" << &g_a << endl;
    cout << "全局变量g_b的地址为:\t" << &g_b << endl;

    static int s_a = 10;
    static int s_b = 10;
    cout << "静态变量s_a的地址为:\t" << &s_a << endl;
    cout << "静态变量s_b的地址为:\t" << &s_b << endl;

    // 常量 
    const int c = 10;

    // 字符串常量
    const string p = "hello world";
    cout << "字符串常量的地址为:\t" << &("hello world") << endl;
    cout << "全局常量c_g_a的地址为:\t" << &c_g_a << endl << endl;

    const int c_l_a = 10;
    const int c_l_b = 10;
    cout << "局部常量c_l_a的地址为:\t" << &c_l_a << endl;
    cout << "局部常量c_l_b的地址为:\t" << &c_l_b << endl;
   

    return 0;
}

代码区

复制代码
1. 存放CPU执行的机器指令
2. 代码区是共享的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可。
3. 代码区是只读的,使其只读的原因是防止程序意外的修改了它的指令

1.2 程序运行后

栈区

复制代码
1. 栈区的数据由编译器管理开辟和释放,在函数执行的期间自动分配,函数执行完毕,自动释放
2. 栈区的注意事项  -- 不要返回局部变量的地址
cpp 复制代码
#include <iostream>
using namespace std;

//栈区的注意事项  -- 不要返回局部变量的地址
//栈区的数据由编译器管理开辟和释放,在函数执行的期间自动分配,函数执行完毕,自动释放

int* func(){
    int a = 10; // 局部变量 存放在栈区,函数执行完毕后自动释放

    return &a; // 返回局部变量的地址
}

int main(int argc, char const *argv[])
{

    int * p = func();
    cout << p << endl; // 野指针
    return 0;
}

堆区

复制代码
由程序员分配释放,若程序员不释放,程序结束时由操作系统回收
利用new关键字,可以将数据开辟到堆区
cpp 复制代码
// 堆区开辟数据

int* func(){
    // 利用new关键字,可以将数据开辟到堆区
    // 指针本质也是局部变量 是放在栈区,指针指向的数据在堆区
    int* a = new int(10);

    return a; // 返回局部变量的地址
}

int main(int argc, char const *argv[])
{

    // 在堆区开辟数据
    int *p = func();
    cout << *p << endl;
    cout << p << endl;
    
    return 0;
}

1.3 new 操作符

复制代码
c++中用new操作符在堆区开辟数据
在堆区开辟的数据,由程序员手动开辟,手动释放
cpp 复制代码
// 在堆区利用new 开辟数组
void test02(){
    int* arr = new int[10];
    for (int i = 0; i < 10; i++){
        arr[i] = i + 100;
    }
    for (int i = 0; i < 10; i++){
        cout << arr[i] << endl;
    }
    //释放堆区数据
    delete[] arr;
}

int main(int argc, char const *argv[])
{

    // 在堆区开辟数据
    test02();
    return 0;
}
相关推荐
pop_xiaoli32 分钟前
UI学习—cell的复用和自定义cell
学习·ui·ios
rui锐rui44 分钟前
大模型学习
学习
YKPG2 小时前
C++学习-入门到精通【14】标准库算法
c++·学习·算法
zm2 小时前
极限复习c++
开发语言·c++
potender2 小时前
前端基础学习html+css+js
前端·css·学习·html·js
程序猿本员2 小时前
线程池精华
c++·后端
靡樊3 小时前
Socket编程UDP\TCP
网络·c++·学习·tcp/ip·udp
余渔鱼11233 小时前
ajax学习手册
学习·ajax·okhttp
东京老树根3 小时前
SAP学习笔记 - 开发24 - 前端Fiori开发 Filtering(过滤器),Sorting and Grouping(排序和分组)
笔记·学习
byte轻骑兵3 小时前
【C++高级主题】命令空间(五):类、命名空间和作用域
开发语言·c++