【C语言】分配内存:malloc() 和 free()

malloc():用于分配内存,但没有给内存指定名字,它返回那块内存第一个直接的地址;如果malloc()找不到所需的空间,它就会返回一个空指针;

free():与malloc() 搭配使用;它的参数是先前malloc() 返回的地址,是一个指针;它释放先前分配的内存;不能用free()来释放通过其他方式分配的内存;

exit():该函数用于在分配失败时结束程序;值EXIT_FAILURE指示程序异常终止;值EXIT_SUCCESS(或者,等同于0)指示程序正常终止;

这样,所分配的内存的持续时间从malloc()分配内存开始,到free()释放内存为止;并且内存块可在一个函数中创建,在另一个函数中释放;

在头文件 stdlib.h 中有malloc() 和 free() 和exit() 的原型;

free() 的重要性:因为被分配的内存只会增加,除非你记得使用free();

malloc(),free()的使用方式:

1 double * ptd;
2 ptd = (double *) malloc(30 * sizeof(double));
3 //另一种方式,实现相当于变长数组,但更灵活
4 int n;
5 ptd = (double *) malloc(n * sizeof(double));
6 //对ptd进行操作
7 free(ptd);

 

来看一个实例:

 1 #include<stdio.h>
 2 #include<stdlib.h>      //为malloc(),free(),exit()函数提供原型
 3 int main(void){
 4     double * ptd;
 5     int max;
 6     int number;
 7     int i=0;
 8     puts("what's the maximum number of type double entires?");
 9     scanf("%d",&max);
10     ptd = (double *)malloc(max * sizeof(double));
11     if(ptd == NULL){
12         puts("Memory allocation failed. Goodbye.");
13         exit(EXIT_FAILURE);
14     }
15     //ptd现在指向有max个元素的数组
16     puts("Enter the value:");
17     while(i < max && scanf("%lf",&ptd[i]) == 1){
18         ++i;
19     }
20     printf("Here are your %d entires: \n", number = i);
21     for (i=0; i<number; i++){
22         printf("%7.2f", ptd[i]);
23         if(i % 7 == 6){
24             putchar('\n');
25         }
26     }
27     if(i % 7 != 0) putchar('\n');
28     puts("Done");
29     free(ptd);      //释放内存,很重要
30 
31     return 0;
32 }

 

运行结果:

函数calloc(): 内存分配到另一种方式:它的特性是使块中全部的位置都置为0

long * newmem;

newmem = (long *) calloc(100, sizeof(long));

第一个参数是所需内存单元的数量,第二个参数是每个单元以字节计的大小;也是使用free()来释放它所分配的内存

 动态分配内存和变长数组:

1 int n=5;
2 int m=6;
3 int ar1[n][m];  //n*m的变长数组
4 int (* p1)[6];  //在c99之前可以使用
5 int (* p2)[m];  //要求变长数组支持
6 p1 = (int (*)[6]) malloc(n*6*sizeof(int));  //n*6数组
7 p2 = (int(*)[m]) malloc(n*m*sizeof(int));   //n*m数组

 

posted on 2018-05-22 21:22  Tsn_Tse  阅读(271)  评论(0编辑  收藏  举报

导航