• C++动态内存分配


    笔者介绍:姜雪伟,IT公司技术合伙人,IT高级讲师,CSDN社区专家,特邀编辑,畅销书作者,已出版书籍:《手把手教你架构3D游戏引擎》电子工业出版社和《Unity3D实战核心技术详解》电子工业出版社等。

    CSDN视频网址:http://edu.csdn.net/lecturer/144

    C / C ++中的动态内存分配是指程序员手动执行内存分配, 动态分配的内存分配给堆,非静态和局部变量获取在Stack上分配的内存。详情查看上篇博文:C程序的内存布局

    什么是应用程序?
    动态分配的内存的一个用途是分配可变大小的内存,除了可变长度数组之外,编译器是不可能分配内存的。
    最重要的用途是为程序员提供灵活性,每当我们需要,并且我们不再需要了, 我们可以随时分配和释放内存,很多情况下,这种灵活性有所帮助, 这种例子是链接列表,树等。

    与分配给正常变量的内存有什么不同?
    对于“int a”,“char str [10]”等常规变量,内存将自动分配和释放。 对于动态分配的内存,如“int * p = new int [10]”,程序员有责任在不再需要时释放内存。 如果程序员没有释放内存,它会导致内存泄漏(内存没有释放,直到程序终止)。

    什么是内存泄漏,如何避免?

    当程序员在堆中创建内存并忘记删除内存时,会发生内存泄漏,内存泄漏对于程序而言是特别严重的问题。以下是内存泄漏的代码:

    [cpp] view plain copy
     
    1. /* Function with memory leak */  
    2. #include <stdlib.h>  
    3.    
    4. void f()  
    5. {  
    6.    int *ptr = (int *) malloc(sizeof(int));  
    7.    
    8.    /* Do some work */  
    9.    
    10.    return; /* Return without freeing ptr*/  
    11. }  

    为了避免内存泄漏,分配给堆上的内存应该不再需要时被释放。

    [cpp] view plain copy
     
    1. #include <stdlib.h>;  
    2.    
    3. void f()  
    4. {  
    5.    int *ptr = (int *) malloc(sizeof(int));  
    6.    
    7.    /* Do some work */  
    8.    
    9.    free(ptr);  
    10.    return;  
    11. }  

    如何在C ++中分配/释放内存?
    C使用malloc()和calloc()函数在运行时动态分配内存,并使用free()函数释放动态分配的内存。 C ++支持这些功能,并且还有两个运算符new和delete来执行分配和释放内存的任务。
    这篇文章是关于new和delete的操作符。

    new 操作符

    new操作符表示堆上的内存分配请求。 如果有足够的内存可用,new操作符初始化内存并将新分配和初始化的内存的地址返回给指针变量。

    使用new操作符的语法:要分配任何数据类型的内存,语法为:

    pointer-variable = new data-type;

    这里,指针变量是数据类型类型的指针,数据类型可以是任何内置数据类型,包括数组或任何用户定义的数据类型,包括结构和类。

    // Pointer initialized with NULL
    // Then request memory for the variable
    int *p = NULL; 
    p = new int;   
    
                OR
    
    // Combine declaration of pointer 
    // and their assignment
    int *p = new int; 

    初始化内存,我们可以使用new 初始化内存

    pointer-variable = new data-type(value);
    Example:
    int *p = new int(25);
    float *q = new float(75.25);

    分配内存块:new运算符也用于分配数据类型的内存块(数组)。

    pointer-variable = new data-type[size];

    其中size(一个变量)指定数组中的元素数。

    int *p = new int[10]

    动态地为类型int连续分配10个整数的内存,并返回指向序列的第一个元素的指针,分配给p(指针), p [0]是指第一个元素,p [1]是指第二个元素等等。

    数组声明用new操作符

    声明数组和使用new内存块分配最重要的区别是,数组由编译器释放(如果数组是本地的,则在函数返回或完成时释放)。 但是,动态分配的数组总是保留在那里,直到它们被程序员或程序终止释放。

    如果运行时内存不足,怎么办?
    如果堆中没有足够的内存可用于分配,则new请求通过抛出类型为std :: bad_alloc的异常来指示失败,而new操作符返回一个指针。 因此,在使用该程序之前,检查新的指针变量可能是一个好主意。

    int *p = new int;
    if (!p)
    {
       cout << "Memory allocation failed
    ";
    }

    delete操作符

    既然程序员有责任释放动态分配的内存,所以使用C ++语言为程序员提供了delete操作符。

    delete pointer-variable;

    这里,指针变量是指向由new创建的数据对象的指针。
    例子:

      delete p;
      delete q;

    要释放由指针变量指向的动态分配的数组,请使用以下形式的delete:

    // Release block of memory 
    // pointed by pointer-variable
    delete[] pointer-variable;  
    
    Example:
       // It will free the entire array
       // pointed by p.
       delete[] p;

    完整的案例代码如下所示:

    [cpp] view plain copy
     
    1. #include <iostream>  
    2. using namespace std;  
    3.    
    4. int main ()  
    5. {  
    6.     // Pointer initialization to null  
    7.     int* p = NULL;  
    8.    
    9.     // Request memory for the variable  
    10.     // using new operator  
    11.     p = new int;  
    12.     if (!p)  
    13.         cout << "allocation of memory failed ";  
    14.     else  
    15.     {  
    16.         // Store value at allocated address  
    17.         *p = 29;  
    18.         cout << "Value of p: " << *p << endl;  
    19.     }  
    20.    
    21.     // Request block of memory  
    22.     // using new operator  
    23.     float *r = new float(75.25);  
    24.    
    25.     cout << "Value of r: " << *r << endl;  
    26.    
    27.     // Request block of memory of size n  
    28.     int n = 5;  
    29.     int *q = new int[n];  
    30.    
    31.     if (!p)  
    32.         cout << "allocation of memory failed ";  
    33.     else  
    34.     {  
    35.         for (int i = 0; i < n; i++)  
    36.             q[i] = i+1;  
    37.    
    38.         cout << "Value store in block of memory: ";  
    39.         for (int i = 0; i < n; i++)  
    40.             cout << q[i] << " ";  
    41.     }  
    42.    
    43.     // freed the allocated memory  
    44.     delete p;  
    45.     delete r;  
    46.    
    47.     // freed the block of allocated memory  
    48.     delete[] q;  
    49.    
    50.     return 0;  
    51. }  

    输出结果:

    Value of p: 29
    Value of r: 75.25
    Value store in block of memory: 1 2 3 4 5 

    http://www.woaipu.com/shops/zuzhuan/61406
    http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117777
    http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117890
    http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117994
    http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=118376



  • 相关阅读:
    【mysql】八、mysql的学习---查询缓存
    【mysql】七、mysql的学习---应用优化
    【mysql】六、mysql的学习---SQL优化
    【mysql】五、mysql的学习---存储引擎
    【mysql】四、mysql的学习---触发器
    【mysql】三、mysql的学习---存储过程和函数
    【mysql】二、mysql的学习---视图
    server --SSD中,SATA,m2,PCIE和NVME各代表了什么,关系是什么
    windows--禁用驱动程序强制签名
    linux --kernel 和 OS 的关系区别
  • 原文地址:https://www.cnblogs.com/sy646et/p/7203153.html
Copyright © 2020-2023  润新知