关于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;


你可能感兴趣的:(关于realloc())