C++【堆内存的动态分配与释放(new/delete)】

C语言分配动态内存常用函数:malloc/calloc/realloc/free
C++语言用new/delete:详见memory.cpp
1.通过new运算符分配单个变量
数据类型* 指针变量 = new 数据类型(初值); int* p2 = new int;int* p3 = new int (100);
2.通过new运算符分配数组 int* p4 = new int[5]; int* p5 = new int[5] {10, 20, 30};
数据类型* 指针变量 = new 数据类型[数组长度] {元素初值, …};
3.对于单个变量用delete销毁,而对于数组用delete[]销毁 delete[] p4;
4.定位分配
数据类型* 指针变量 = new(起始地址) 数据类型(初值);
起始地址所标记的内存应该事先分配好。
5.new在分配内存(malloc)之后还会调用构造函数,delete/delete[]在释放内存(free)之前先调用析构函数。

// 堆内存的动态分配与释放
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main (void) {
    int* p1 = (int*)malloc (sizeof (int));
    cout << *p1 << endl;
    free (p1);
// free (p1);
    p1 = NULL;
// *p1 = 100;
// cout << *p1 << endl;
    int* p2 = new int;
    cout << *p2 << endl;
    delete p2;
// delete p2;
    p2 = NULL;
    int* p3 = new int (100);
    cout << *p3 << endl;
    delete p3;
    p3 = NULL;
    int* p4 = new int[5];
    for (size_t i = 0; i < 5; i++)
        p4[i] = i;
    for (size_t i = 0; i < 5; i++)
        cout << p4[i] << ' ';
    cout << endl;
    delete[] p4;
    p4 = NULL;
    int* p5 = new int[5] {10, 20, 30};
    for (size_t i = 0; i < 5; i++)
        cout << p5[i] << ' ';
    cout << endl;
    delete[] p5;
    p5 = NULL;
    int* p6 = (int*)malloc (
        sizeof (int) * 0xFFFFFFFF);
    if (! p6)
        perror ("malloc");
    else {
        free (p6);
        p6 = NULL;
    }
    /* int* p7 = NULL; try { p7 = new int[0xFFFFFFFF]; } catch (exception& ex) { cout << ex.what () << endl; cout << "请扩大内存!" << endl; return -1; } delete[] p7; p7 = NULL; */
// int (*p8)[4] =
// (int (*)[4])malloc (3 * 4 * sizeof (int));
    int (*p8)[4] = new int[3][4];
    for (size_t i = 0; i < 3; i++)
        for (size_t j = 0; j < 4; j++)
            p8[i][j] = i * 4 + j;
    for (size_t i = 0; i < 3; i++) {
        for (size_t j = 0; j < 4; j++)
            cout << setw (4) << p8[i][j];
        cout << endl;
    }
// free (p8);
    delete[] p8;
    p8 = NULL;
    char buf[4];
    int* p9 = new (buf) int;//数据类型* 指针变量 = new(起始地址) 数据类型(初值);
    *p9 = 0x12345678;
    printf ("%#x %#x %#x %#x\n", buf[0], buf[1],
        buf[2], buf[3]);
// delete p9;
    return 0;
}

运行结果:
0
0
100
0 1 2 3 4
10 20 30 3 4
malloc: Cannot allocate memory
0 1 2 3
4 5 6 7
8 9 10 11
0x78 0x56 0x34 0x12

你可能感兴趣的:(delete,new,动态内存)