正确使用Realloc
这是我被教导使用realloc()
:
int *a = malloc(10); a = realloc(a, 100); // Why do we do "a = .... ?" if(a == NULL) //Deal with problem.....
这不是多余的吗? 我不能这样做吗? :
if(realloc(a, 100) == NULL) //Deal with the problem
我发现的其他realloc示例也是如此,例如:
int *oldPtr = malloc(10); int * newPtr = realloc(oldPtr, 100); if(newPtr == NULL) //deal with problems else oldPtr = newPtr;
我不能这样做吗? :
int *oldPtr = malloc(10); if(realloc(oldPtr, 100) == NULL) //deal with problems //else not necessary, oldPtr has already been reallocated and has now 100 elements
realloc
返回指向resize的缓冲区的指针; 此指针值可能与原始指针值不同,因此您需要在某处保存该返回值。
如果请求无法满足,则realloc
可能返回NULL
(在这种情况下,原始缓冲区保留在原位)。 因此,您希望将返回值保存到与原始不同的指针变量。 否则,您可能会冒险使用NULL
覆盖原始指针并丢失对该缓冲区的唯一引用。
例:
size_t buf_size = 0; // keep track of our buffer size ... int *a = malloc( sizeof *a * some_size ); // initial allocation if ( a ) buf_size = some_size; ... int *tmp = realloc( a, sizeof *a * new_size ); // reallocation if ( tmp ) { a = tmp; // save new pointer value buf_size = new_size; // and new buffer size } else { // realloc failure, handle as appropriate }
realloc on failure保留原始指针和大小。 成功时的realloc可能不会(通常也不会)返回与输入完全相同的指针。
所以正确的解决方案是你的第三个例子。
int *oldPtr = malloc(10); int * newPtr = realloc(oldPtr, 100); if(newPtr == NULL) //deal with problems else oldPtr = newPtr;
调用realloc
的正确方法是将返回值保存在临时变量中并检查它是否为NULL。 这样,如果realloc失败,你就没有丢失原始内存。 例如:
int *a, *b; a = malloc(10); b = realloc(a, 100); if (b == NULL) { // handle error and exit } a = b;
编辑:请注意,如果error handling没有退出,你应该把最后一行放在上面,即a = b;
在else子句中。
此代码段错误。
int *a = malloc(10); a = realloc(a, 100); // Why do we do "a = .... ?" if(a == NULL) //Deal with problem.....
如果realloc
的调用返回NULL
则指针a
的先前值将丢失。 因此可能存在内存泄漏,因为无法释放由malloc
调用分配的malloc
。
如果只是为了写
if(realloc(a, 100) == NULL) //Deal with the problem
然后反过来, realloc
调用的返回指针可能会丢失。
此代码段
int *oldPtr = malloc(10); int * newPtr = realloc(oldPtr, 100); if(newPtr == NULL) //deal with problems else oldPtr = newPtr;
是正确的。 但是如果要写
int *oldPtr = malloc(10); if(realloc(oldPtr, 100) == NULL) //deal with problems //else not necessary, oldPtr has already been reallocated and has now 100 elements
然后再次返回realloc
调用的指针可能会丢失。
来自C标准中realloc
的描述(7.22.3.5 realloc函数)
4 realloc函数返回一个指向新对象的指针(可能具有( 或者可能没有 ) 由我添加的指针与指向旧对象的指针相同的值,如果无法分配新对象,则返回空指针。