主要初步介紹malloc、free、calloc、realloc的基本。日后會有更詳細的內容。
malloc、free分別用於動態內存分配和釋放。
malloc會從內存池里提取一塊合適的內存(連續的),並返回指向這塊內存(起始位置的指針,該指針的類型為void*指針(因為malloc不知道你請求的內存需要存儲的數據類型),而且這塊內存並沒有初始化。
如果操作系統無法提供給malloc足夠的內存,malloc就會返回一個NULL指針。因此必須對每個從malloc返回的指針進行檢查。
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6 int *pi;
7 int i;
8 pi = malloc( 25 * sizeof( int ));
9
10 if( pi == NULL )
11 {
12 printf( " Out of memory!\n " );
13 exit( 1);
14 }
15
16 for(i = 0; i != 25; i++)
17 pi[i] = i;
18
19 for(i = 0; i != 25; i++)
20 printf( " %d ", pi[i]);
21 printf( " \n ");
22
23 return 0;
2 #include <stdlib.h>
3
4 int main()
5 {
6 int *pi;
7 int i;
8 pi = malloc( 25 * sizeof( int ));
9
10 if( pi == NULL )
11 {
12 printf( " Out of memory!\n " );
13 exit( 1);
14 }
15
16 for(i = 0; i != 25; i++)
17 pi[i] = i;
18
19 for(i = 0; i != 25; i++)
20 printf( " %d ", pi[i]);
21 printf( " \n ");
22
23 return 0;
24 }
calloc也可以用於內存分配,但是返回指向內存的指針之前會初始化為0。而且calloc和malloc請求內存數量的方式也不一樣。
realloc用於修改一個原先已經分配的內存大小。PS:若原來的內存塊無法改變大小,realloc將分配另一塊正確的小的內存,並把原來的那塊內存的內容復制到新的內存塊。
free函數的參數為一個先前從malloc、calloc、realloc返回的值。對NULL指針不會產生任何效果。
動態內存分配最常見的錯誤是忘記檢查請求的內存是否分配成功。
《C與指針》里面提供了一個程序可以減少錯誤的內存分配器。
代碼如下:
1 #include <stdlib.h>
2
3 #define malloc // 用於防止由於其他代碼塊直接塞入程序而導致偶爾直接調用malloc
4 #define MALLOC(num, type) (type *)alloc((num) * sizeof(type)) // 接受元素的數目和類型,調用alloc函數獲得內存,alloc調用malloc並進行檢查,確保返回的指針不是NULL
2
3 #define malloc // 用於防止由於其他代碼塊直接塞入程序而導致偶爾直接調用malloc
4 #define MALLOC(num, type) (type *)alloc((num) * sizeof(type)) // 接受元素的數目和類型,調用alloc函數獲得內存,alloc調用malloc並進行檢查,確保返回的指針不是NULL
5 extern void *alloc( size_t size );
1 #include <stdio.h>
2 #include " alloc.h "
3 #undef malloc
4
5 void *alloc( size_t size )
6 {
7 void *new_mem;
8 /*
9 * 請求所需的內存,並檢查是否分配成功
10 */
11 new_mem = malloc( size );
12 if( new_mem == NULL )
13 {
14 printf( " Out of memory!\n " );
15 exit( 1);
16 }
17 return new_mem;
2 #include " alloc.h "
3 #undef malloc
4
5 void *alloc( size_t size )
6 {
7 void *new_mem;
8 /*
9 * 請求所需的內存,並檢查是否分配成功
10 */
11 new_mem = malloc( size );
12 if( new_mem == NULL )
13 {
14 printf( " Out of memory!\n " );
15 exit( 1);
16 }
17 return new_mem;
18 }
1 #include <stdio.h>
2 #include
"
alloc.h
"
3
4 int main()
5 {
6 int *new_memory;
7 int i;
8
9 /*
10 * 獲得一個整型數組
11 */
12 new_memory = MALLOC( 25, int );
13
14 for(i = 0; i != 25; i++)
15 new_memory[i] = i;
16
17 for(i = 0; i != 25; i++)
18 printf( " %d ", new_memory[i]);
19 printf( " \n ");
20 return 0;
21 }
3
4 int main()
5 {
6 int *new_memory;
7 int i;
8
9 /*
10 * 獲得一個整型數組
11 */
12 new_memory = MALLOC( 25, int );
13
14 for(i = 0; i != 25; i++)
15 new_memory[i] = i;
16
17 for(i = 0; i != 25; i++)
18 printf( " %d ", new_memory[i]);
19 printf( " \n ");
20 return 0;
21 }