1. 程式人生 > >C++【堆記憶體的動態分配與釋放(new/delete)】

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