介紹malloc, free ,calloc, realloc , new, delete
1. malloc , free
功能 => 動態配置記憶體
用法 int *ptr = malloc(sizeof(int));
malloc配置一個int的空間(4byte),並回傳空間的位址
用指標ptr來儲存這個位址,此程式只配置空間但不初始空間中的 儲存值
在整個程式結束前並不會自動歸還記憶體,必須使用 free()函式將空間釋放
範例如下:
int *ptr = malloc(sizeof(int));
printf("address: %X
", ptr);
printf("variable: %d
", *ptr);
*ptr = 200;
printf("address: %X
", ptr);
printf("variable: %d
", *ptr);
free(ptr);
==========會印出=============
建立空間的位置a
指向的值 (未知)
建立空間的位置a
200
2. calloc
功能 =>做動態的記憶體配置, 且會將空間初始為0
用法 int *arr = calloc(1000, sizeof(int)); //配置1000各int大小的空間
同樣的 要用free歸還記憶體
範例如下:
int *nPtr = calloc(100, sizeof(int));
printf("
");
printf("%X
", nPtr);
printf("%d
", *nPtr);
*nPtr = 10;
printf("%X
", nPtr);
printf("%d
", *nPtr);
free(ptr);
==========會印出=============
建立空間的位置a
0
建立空間的位置a
10
3. realloc
功能: 做動態記憶體配置, 且可以改變由malloc , calloc, realloc所配置的記憶體空間大小
用法: realloc(ptr, 25); //ptr為原先空間的指標, 25為新空間的大小, 調整成功會回傳新的空間大小, 失敗的話回傳NULL
以下為範例:
char *ptr;
ptr = malloc(23);
if (ptr == NULL) {
printf("建立記憶體區域失敗...
");
exit(1);
}
strcpy(ptr, "History repeats itself.");
ptr = realloc(ptr, 25);
if(ptr == NULL) {
printf("擴充記憶體區域失敗...
");
exit(1);
}
strcat(ptr, "
");
printf(ptr);
free(ptr);
4. new 和 delete
功能:做動態的記憶體配置, 為C++的語法!
用法: 與malloc類似, 且new也是搭配delete來釋放記憶體
範例
int *ptr = new int(77);
printf("
");
printf("%X
", ptr);
printf("%d
", *ptr);
*ptr = 88;
printf("%X
", ptr);
printf("%d
", *ptr);
delete ptr;
==========會印出=============
建立空間的位置a
77
建立空間的位置a
88
總結及比較
a)
malloc和calloc差異在於兩種寫法不同,以及calloc配置空間的值為0
int *ptr = malloc(5*sizeof(int));
int *ptr2 = calloc(5,sizeof(int));
b)
C 使用 malloc、free;而 C++ 使用 new、delete
new 與 delete 是運算子 (operator)
而 malloc 與 free 只是普通的函數 (ordinary function)
參考資料:
http://openhome.cc/Gossip/CGossip/MallocFree.html
http://pydoing.blogspot.tw/2010/07/c-realloc.html
';$(".articleExtAd").append(notVIP);setTimeout(function() {$('.top-toolbar').data('top-toolbar').setAD({title: "[C Program] malloc ,free ,calloc, realloc , new, delete\u4ecb\u7d39",label_id: 164,label_name: "\u8edf\u9ad4\u60c5\u5831"});}, 2000);


- 日誌
- 相簿
- 影音

facebook_phoenix's 新文章
- opts用法解析
- Android Program Architecture 架構 (Android Studio)
- sizeof 整數所占記憶體空間 (32bit and 64bit 比較)
- Python入門語法
- include 的路徑 (" 冒號 和 < 括號的區別)
- C 陣列(Array)與結構(Structure)筆記
- C 指標宣告 用法 筆記 (一)
- [C Program] typedef ,enum 用法
- [C Program] malloc ,free ,calloc, realloc , new, delete介紹
- [C Program] 指標與遞增問題
facebook_phoenix's 新回應
- 沒有新回應!
- AAA





Powered by Xuite
離婚證人