C/C++——C和C++怎樣分配和釋放記憶體,區別是什麼?

readyao發表於2015-12-28

C語言分配記憶體的函式:

#include <stdlib.h>
void *malloc(size_t size);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);

malloc函式分配大小為size位元組的記憶體空間,返回一個指標指向申請的該記憶體的首地址,該記憶體區域沒有被初始化。
calloc函式分配大小為nmemb*size位元組的記憶體空間(nmemb是資料的大小,size是每個資料的大小),返回一個指標指向申請的該記憶體的首地址,該記憶體區域被初始化為0。
realloc函式改變之前ptr指向的記憶體的大小。重新分配大小為size位元組的記憶體空間,返回一個指標指向申請的該記憶體的首地址。

C語言釋放記憶體的函式:

#include <stdlib.h>
void free(void *ptr);
free用來釋放由malloc,calloc,realloc分配的記憶體,free的引數是它們三個函式的返回值(指向動態記憶體的指標);

下面是man手冊對這四個函式詳細講解:(可以自己查一下:在終端輸入命令man malloc然後就出現了這四個函式的介紹)

The malloc() function allocates size bytes and returns a pointer to the allocated memory.  The memory is not initialized.  If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc().  Otherwise, or  if free(ptr) has already been called before, undefined behavior occurs.  If ptr is NULL, no operation is performed.

The  calloc()  function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory.  The memory is set to zero.If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

The realloc() function changes the size of the memory block pointed to by ptr to size bytes.  The contents will be unchanged in the  range  from  the  start  of  the region  up to the minimum of the old and new sizes.  If the new size is larger than the old size, the added memory will not be initialized.  If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).  Unless  ptr  is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().  If the area pointed to was moved, a free(ptr) is done.

C++用new來分配記憶體,用delete來釋放記憶體。

1、申請單個物件,比如int物件(變數)
int *p = new int;

int *p = new int(100);
2、申請陣列
int *p = new int[100];
3、釋放單個物件
delete p;
4、釋放陣列
delete [] p;

例項:

#include<iostream>
using namespace std;

int main()
{
    int *p = new int;
    *p = 99;
    cout << "*p is " << *p << endl;
    int *p2 = new int(100);
    cout << "*p2 is " << *p2 << endl;

    int  *parray = new int[10];
    cout <<"申請一個int陣列,大小為10,記憶體已經初始化為0了,現在列印這十個初始化的數值\n";
    for (int i = 0; i < 10; i++){
        cout << *(parray+i) << ", ";
    }
    cout << endl;

    cout << "釋放記憶體p\n";
    delete p;
    cout << "釋放記憶體p2\n";
    delete p2;
    cout << "釋放該int陣列\n";
    delete [] parray;

    return 0;
}


兩者的區別:

1、new和delete是C++動態申請記憶體和釋放記憶體的運算子,不是一個標準庫中的函式。

2、new分配的物件會呼叫解構函式,malloc分配的是一塊記憶體區域。


推薦一個連結:

http://www.nowamagic.net/librarys/veda/detail/2427

相關文章