标准库函数malloc/calloc/realloc以及free的堆内存分配与回收
1 /* 2 * malloc练习 3 * 4 * */ 5 6 #include <stdlib.h> 7 #include <stdio.h> 8 9 int main() 10 { 11 int *p_value = NULL; 12 13 p_value = (int *) malloc (1 * sizeof(int)); 14 if (p_value) { 15 printf(" p_value是0x%p\n", p_value); 16 printf("*p_value是%d\n", *p_value); 17 free(p_value); 18 p_value = NULL; 19 } 20 } 21 22 return 0; 23 }
1 /* 2 * calloc(), realloc()练习 3 * 4 * 不同于malloc,calloc会将把开辟的存储空间初始化为零 5 * 6 * */ 7 8 #include <stdlib.h> 9 #include <stdio.h> 10 11 int main() 12 { 13 int *p_value = (int * ) calloc(4, sizeof(int)); 14 //(int * ) malloc(4 * sizeof(int)); 15 if (p_value) { 16 printf(" p_value是0x%p\n", p_value); 17 printf("*p_value是%d\n", *p_value); 18 void *pointer = NULL; 19 pointer = realloc(p_value, 6 * sizeof(int)); 20 //realloc(p_value, 0);实际效果就等于语句free(p_value); 21 //p_value = NULL, realloc(p_value, 4*sizeof(int));实际效果就 22 //等于语句p_value = NULL, p_value = (int *)malloc(4*sizeof(int)); 23 if (pointer) { 24 p_value = (int * )pointer; 25 } 26 printf(" p_value是0x%p\n", p_value); 27 printf("*p_value是%d\n", *p_value); 28 free(p_value); 29 p_value = NULL; 30 } 31 }
1 /* 2 * Input: 1234 3 * Output: 4321 4 * */ 5 6 #include <stdio.h> 7 #include <stdlib.h> 8 9 int main() 10 { 11 typedef enum {N, Y} en_retry; 12 13 en_retry over = N; 14 int *p_integer = NULL; 15 int *p_integers[100] = {NULL}; 16 17 int counter = 0; 18 do { 19 p_integer = (int *) malloc(sizeof(int) * 1); 20 if (p_integer) { 21 printf("Input an Integer"); 22 scanf("%d", p_integer); 23 p_integers[counter++] = p_integer; 24 } 25 printf("Another?[Y/N]"); 26 printf("%d\n", over); 27 scanf("%d", &over); 28 printf("%d\n", over); 29 } while (over); 30 31 for (--counter; counter >= 0; counter--) { 32 printf("%d\t", *p_integers[counter]); 33 free(p_integers[counter]); 34 } 35 printf("\n"); 36 37 return 0; 38 }