C++详解:关于malloc()

使用:

原型:

extern void *malloc(unsigned int num_bytes);

头文件:

#include<malloc.h>

        或:

#include<alloc.h>

        (二者内容完全一致)

功能:分配长度为num_bytes字节的内存(块),会返回指向该内存的指针

                若内存不足,则返回NULL。

检查:同动态内存(见C++动态内存)一样,我们可以使用判断语句检查内存是否足够:

int a=(int*)malloc(100);    //分配长度为100bytes的内存空间。
                            //注意在malloc()前加上指针类型转换,以免出现意想不到的错误

try{
    if(!a){throw"Out of memory!";}
}catch(const char* e){std::cerr<<e;}

free(a);

在内存不再被需要时,应该使用free()释放内存,与delete关键字相似。

注意:

        malloc()的声明为

void *malloc(unsigned int num_bytes);

它的返回类型为void*,这表示未确定类型的指针,因此我们在使用时要加上(type*)以强制将void*转换其他类型。(C/C++规定,void*可以强制转换为任何其他类型的指针具体内容如下:)

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.

malloc()与new的不同:

从函数声明上可以看出。malloc 和 new 至少有两个不同: new 返回指定类型的指针,并且可以自动计算所需要大小。

int a=new int;    //分配int类型所需长度(即sizeof(int))的内存空间,且返回int*指针。

int b=(int*)malloc(sizeof(int));    //(同),但返回为void*,必须强制转换,否则会报错。
                                    //并且所分配的内存大小自定
#if 0
    如果写作:
int x=(int*)malloc(1);
    则会有3内存无家可归,导致后面的内存的值被清空
#endif

new运算符可以分配一串内存(用来存数组),实际上,malloc()也可以:

int a[100]=new int[100];

与下面这句作用相同:

int a[100]=(int*)malloc(sizeof(int)*100);//100个sizeof(int)的大小

        另外有一点不能直接看出的区别是,malloc 只管分配内存,并不能对所得的内存进行初始化,所以得到的一片新内存中,其值将是随机的。

        除了分配&释放时的区别,其他时候,malloc()和new几乎无差别。

----------------------------------------------~~~~~>END<~~~~~--------------------------------------------

  • 11
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值