C 語言的記憶體配置很簡單: malloc、calloc、realloc、free
malloc(位元組數); 返回記憶體段的首地址, void 的.
calloc(個數, 類型大小); 和 malloc 的區別就是它會初始化記憶體為空白.
realloc(原指標, 位元組數); 重新分配由 malloc、calloc 分配的記憶體; 這裡有太多注意事項:
1、如果縮小了, 會截掉一塊, 會保留前面的內容;
2、如果擴大了, 仍會保留已有的內容, 但新加的記憶體不會初始化;
3、在擴大時, 有可能記憶體位址會變化, 這樣原來的指標就廢了, 不過傳回值是新指標, 所以繼續使用的應該是傳回值.
如果分配失敗會返回 NULL, 一般是因為記憶體不足; 分配 0 位元組記憶體也會返回 NULL 但這沒有意義.
它們都是用 free(指標) 釋放.
1. 給一個整數分配記憶體:
#include <stdio.h>#include <stdlib.h>int main(void){ int *p = NULL;// p = malloc(sizeof(int)); /* 應該像下一句同時類型轉換, 不然在 C++ 裡面不行 */ p = (int *)malloc(sizeof(int)); *p = 100; printf("%d\n", *p); free(p); getchar(); return 0;}
2. 給 3 個整數分配記憶體:
#include <stdio.h>#include <stdlib.h>int main(void){ int *p = NULL; p = (int *)malloc(sizeof(int)*3); *p = 111; *(p+1) = 222; *(p+2) = 333; printf("%d,%d,%d\n", *p, *(p+1), *(p+2)); free(p); getchar(); return 0;}
3. 像數組一樣使用:
#include <stdio.h>#include <stdlib.h>int main(void){ int *p = (int *)malloc(sizeof(int)*3); p[0] = 111; p[1] = 222; p[2] = 333; printf("%d, %d, %d\n", p[0], p[1], p[2]); free(p); getchar(); return 0;}
4. calloc 會同時初始化記憶體, malloc 則不會, 不初始化應該更快些:
#include <stdio.h>#include <stdlib.h>int main(void){ const int num = 10; // calloc 和 malloc 參數也有點區別 long *p1 = (long *)calloc(num, sizeof(long)); /* 會初始化 */ long *p2 = (long *)malloc(num * sizeof(long)); /* 不會初始化 */ int i; for (i = 0; i
5. realloc:
#include <stdio.h>#include <stdlib.h>int main(void){ int num = 10; int i; long *p = (long *)malloc(num * sizeof(long)); printf("記憶體位址: %p\n~~~~~~~~\n", p); for (i = 0; i
6. 判斷記憶體是否分配成功:
#include <stdio.h>#include <stdlib.h>int main(void){ int *p = (int *)malloc(100); if (p != NULL) printf("分配成功!\n"); if (p) printf("分配成功!\n"); if (p == NULL) printf("記憶體不足!\n"); if (!p) printf("記憶體不足!\n"); free(p); getchar(); return 0;}