关于realloc的使用与分析

//函数原型如下
void* realloc(void* ptr, unsigned newsize);

realloc可以对给定的指针所指的空间进行扩大或者缩小;realloc是从堆上分配内存的.当扩大一块内存空间时,realloc()试图直接从堆上现存的数据后面的那些字节中获得附加的字节,如果能够满足,执行成功;如果数据后面的字节不够,那么就使用堆上第一个有足够大小的自由块,现存的数据被拷贝至新的位置,而老块则放回到堆上,这句话传递的一个重要的信息就是数据可能被移动,realloc并不保证调整后的内存空间和原来的内存空间保持同一内存地址。

 

来看一段代码:

void size(usignedint count)
{
       _arr = (int *)realloc(_arr,count * sizeof(int));
}


此处的_arr指向一片已经分配的堆上内存;该函数会存在什么问题呢?先来看看MSDN上对realloc的介绍。

realloc returns a void pointer to the reallocated (and possibly moved) memory block. Thereturn value is NULL if the size is zero and the buffer argument isnot NULL, or if there is not enoughavailable memory to expand the block to the given size. In the first case,the original block is freed. In thesecond, the original block is unchanged.The return value points to a storage space that is guaranteed to be suitablyaligned for storage of any type of object. To get a pointer to a type otherthan void, use a type cast on the return value.

 

回过头看刚刚的例子:

_arr = (int *)realloc(_arr, count * sizeof(int));

如果realloc申请内存失败,返回NULL,_arr将被置为NULL,原来分配的内存是不变的(originalblock is unchanged),出现内存泄漏,修改代码如下:

void size(usignedint count)
{
       int *temp = (int*)realloc(_arr, count * sizeof(int));
       if(temp == NULL)
       {
              free(_arr);
              _arr = NULL;
       }
       else
       {
              _arr = temp
       }
}

以上代码是否就不存在问题了呢?考虑count为0的情况,如果size为0, 原来申请的内存会被释放掉(original block is freed),如上代码将会出现重复释放内存错误,继续修改如下:

void size(usignedint count)
{
       if(count == 0)
       {
              free(_arr);
              _arr = NULL;
              return;
       }
       int *temp = (int*)realloc(_arr, count * sizeof(int));
       if(temp == NULL)
       {
              free(_arr);
              _arr = NULL;
       }
       else
       {
              _arr = temp
       }
}

篇幅问题,代码不考虑_arr == NULL的情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值