7.4.4 用malloc分配内存单元
除了new/delete外,C++(www.cppentry.com)中还保留了C中分配动态内存的方法。C中使用malloc/free对来分配和释放动态内存,这和new/delete比较类似。malloc的原型为:
- extern void *malloc(unsigned int num_bytes);
该函数在头文件malloc.h中,它的功能是申请num_bytes字节的连续内存块。如果申请成功则返回该块的首地址;否则返回空指针NULL。用法如下所示。
- type *p;
- p=(type*)malloc(sizeof(type)*n);
其中,p是type型指针,sizeof(type)是计算一个type型数据需要的字节数,n表示需要存储n个type型数据。(type*)是对malloc的返回值进行强制转换。该式的含义是申请可以存储n个type型数据的内存块,并且将块的首地址转换为type型赋给 p。
当用malloc分配的内存不再使用时,应使用free()函数将内存块释放。格式如下所示。
- free p;
其中,p是不再使用的指针变量。同delete一样,free也没有破坏指针p的内容,只是告诉系统收回这片内存单元,可以重新利用。所以free后,最好将p显示置空指针。
【示例7-11】 演示malloc/free的使用方法。
- p=(char*)malloc(sizeof(char)*2);
- free p;
分析:malloc/free与new/delete的区别在于:前者是C++(www.cppentry.com)/C语言的标准库函数,后者是C++(www.cppentry.com)的运算符,是保留字。malloc返回的是无符号指针,需要强制转换才能赋给指针变量,而new可以返回正确的指针。
说明:malloc只是分配要求的内存单元,而new则可以自动根据类型计算需要的内存空 间。如果有构造函数,new还会自动执行。
【示例7-12】 综合演示指针的使用方法。
- #include <malloc.h>
- int main(void)
- {
- int *pInt1,*pInt2,*pInt3,*pInt4;
- int iVal=100;
- pInt1=&iVal;
- pInt2=pInt1;
- cout<<"address of pInt1 "<<pInt1<<endl;
- cout<<"value of pInt1 "<<*pInt1<<endl;
- cout<<"address of pInt2 "<<pInt2<<endl;
- cout<<"value of pInt2 "<<*pInt2<<endl;
- pInt3=new int;
- *pInt3=200;
- cout<<"address of pInt3 "<<pInt3<<endl;
- cout<<"value of pInt2 "<<*pInt3<<endl;
- pInt4=(int*)malloc(sizeof(int));
- *pInt4=300;
- cout<<"address of pInt4 "<<pInt4<<endl;
- cout<<"value of pInt4 "<<*pInt4<<endl;
- delete pInt3;
- pInt3=0;
- free (pInt4);
- pInt4=0;
- return 0
- }
分析:该示例中定义了4个变量,分别采用4种不同的方法初始化。pInt1被初始化为整型变量iVal的地址,因此pInt1的内容应该是100。pInt2被直接赋于指针pInt1,两者将指向同一内存单元。pInt3用new运算符申请,Int4用mallocf申请。因此,可能的输出为:
- address of pInt1 0x22ff64
- value of pInt1 100
- address of pInt2 0x22ff64
- value of pInt2 100
- address of pInt3 0x3e3f18
- value of pInt2 200
- address of pInt4 0x3e3f98
- value of pInt4 300
其中,0x22ff64等数字是以十六进制表示的地址。
【责任编辑:
云霞 TEL:(010)68476606】