C標准函數庫中,常見的堆上內存管理函數有malloc(), calloc(), recalloc(), free()。
之所以使用堆,是因為棧只能用來保存臨時變量、局部變量和函數參數。在函數返回時,自動釋放所占用的存儲空間。而堆上的內存空間不會自動釋放,直到調用free()函數,才會釋放堆上的存儲空間。
一、具體使用方法
1、malloc()
頭文件:stdlib.h
聲明:void * malloc(int n);
含義:在堆上,分配n個字節,並返回void指針類型。
返回值:分配內存成功,返回分配的堆上存儲空間的首地址;否則,返回NULL
2、calloc()
頭文件:stdlib.h
聲明:void *calloc(int n, int size);
含義:在堆上,分配n*size個字節,並初始化為0,返回void* 類型
返回值:同malloc() 函數
3、recalloc()
頭文件:stdlib.h
聲明:void * realloc(void * p,int n);
含義:重新分配堆上的void指針p所指的空間為n個字節,同時會復制原有內容到新分配的堆上存儲空間。注意,若原來的void指針p在堆上的空間不大於n個字節,則保持不變。
返回值:同malloc() 函數
4、free()
頭文件:stdlib.h
聲明:void free (void * p);
含義:釋放void指針p所指的堆上的空間。
返回值:無
5、memset()
頭文件:string.h
聲明:void * memset (void * p, int c, int n) ;
含義:對於void指針p為首地址的n個字節,將其中的每個字節設置為c。
返回值:返回指向存儲區域 p 的void類型指針。
二、示例代碼
/* * Author: klchang * Description: Test the memory management functions in heap. * Created date: 2016.7.29 */ #include <stdio.h> // scanf, printf #include <stdlib.h> // malloc, calloc, realloc, free #include <string.h> // memset #define SIZE 10 // Input Module int* inputModule(int* ptrCount) { int* arr, d, i = 0; int length = SIZE; // Apply malloc() arr = (int*)malloc(SIZE * sizeof(int)); memset(arr, 0, length * sizeof(int)); // Input module printf("Input numbers until you input zero: \n"); while (1) { scanf("%d", &d); // count *ptrCount += 1; if (0 == d) { arr[i] = 0; break; } else { arr[i++] = d; } if (i >= length) { // Apply realloc() realloc(arr, 2*length*sizeof(int)); memset(arr+length, 0, length * sizeof(int)); length *= 2; } } return arr; } // Output module void outputModule(int* arr, int* ptrCount) { int i; printf("\nOutput all elements that have been input: \n"); for(i = 0; i < *ptrCount; i++) { if (i && i%5 == 0) printf("\n"); printf("\t%d", *(arr+i)); } // Release heap memory space free(ptrCount); free(arr); } int main() { int i = 0; int* ptrCount; int* arr; // Apply calloc() ptrCount = (int *)calloc(1, sizeof(int)); // Input Module arr = inputModule(ptrCount); // Before free() function, output the count of input numbers printf("\n\nBefore using free() function, Count: %d", *ptrCount); // Output Module outputModule(arr, ptrCount); // After free() function, output the count of input numbers printf("\n\nAfter using free() function, Count: %d", *ptrCount); return 0; }
結果圖片
參考資料:
1、C中堆管理——淺談malloc,calloc,realloc函數之間的區別
http://www.cppblog.com/sandywin/archive/2011/09/14/155746.html