关于realloc()

通常,realloc的用法会如下:

p = realloc(p, new_size);
if (p == NULL) {
        return;
}

一次偶然的机会看了一下man,发现这样的用法是有问题的。

man的原文如下:

void *realloc(void *ptr, size_t size);

realloc() changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged to the minimum of the old and new sizes; newly allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to malloc(size); if size is equal to zero, the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done.

RETURN VALUE

realloc() returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails the original block is left untouched; it is not freed or moved.

前面的都没什么问题,重点是最后一句。如果realloc()失败,ptr指向的这块内存不会变化,不会free或者移动。也就是说,如果realloc()失败了,照着上面代码的写法,这块内存就被永远遗忘了。

比较稳妥的做法应该是这样:

tmp = realloc(p, new_size);
if (tmp == NULL) {
        free(p);
        return;
}
p = tmp;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值