堆是内存空间。堆是区别于栈区,全局数据区,代码区的另一个内存区域。堆允许程序在运行时申请某个大小的内存空间。也称为动态内存。
函数malloc()是C程序获得堆内存的一种方法,它是alloc.h头文件中声明。函数原型为:void *malloc(size_t size);size_t即unsigned long.
该函数从堆内存中“切下”一块size大小的内存,将指向该内存的地址返回。该内存中内容未知。
实例:
# include<iostream.h>
#include<alloc.h>
void main()
{
int arraysize;
int *array;
cout<<"input";
cin>>arraysize;
array=(int *)malloc(arraysize * sizeof(int));
for(int count=0;count<arraysize;count++)
{
array[count]=count*2;
for(int count=0;count<arraysize;count++)
cout<<array[count]<<" ";
cout<<endl;
}
}
上例并没有保证一定可以从堆内存中获得所需内存,有时系统提供的堆内存空间不够分配,这时系统会自动返回一个空指针值null。这时所有对该指针的访问都是破坏性的,因此用malloc()函数更完善的代码如下:
if((array=(int *)malloc(arraysize*sizeof(int)))==null)
{
cout<<"cannot allocate more memory,terminating./n";
exit(1);
}
对于函数运行中分配的内存,释放函数为free(),返回分配的堆内存。函数原型为:void free(void *);
free()参数是先前调用的malloc()函数时返回的地址,把其他值传给free()可能会引起灾难性的后果。
比如上例:free(array);释放堆内存。