c-将realloc()分配给不同的指针和将realloc()分配到同一个指针之间有什么区别吗



我对在C中使用动态内存有点陌生,我想知道使用realloc((分配给不同的指针和使用realloc((分配相同的指针之间是否有区别。例如:

int *ptr = calloc(10,sizeof(int))
ptr=(int*)realloc(ptr,20);

*ptr3;
int *ptr = calloc(10,sizeof(int))
ptr3=(int*)realloc(ptr,20);

我已经执行了这两个代码,我看不出这两个码之间有什么真正的区别(意见者的值和内存分配之间也没有区别(。非常感谢。

realloc发生故障时,前者会出现差异;在这种情况下,它返回NULL,但不返回您传递它的原始ptrfree。通过直接重新分配ptr,您可以保证在realloc失败时内存泄漏,因为您不再有指向free的原始指针。

这里看到的规范/正确用法使用两个指针,一个是持久指针,另一个是临时指针。realloc的结果总是放在临时中,以便可以对其进行检查(以及故障时的持久指针free(。在已知重新分配成功后,临时指针将替换持久指针(保证与临时指针相同,或者如果分配无法到位,则无效(。

对于第一种情况,如果realloc失败,则返回一个null指针。然后,您将把null指针分配给ptr,使得free不可能成为ptr最初指向的内存。

相反,请执行以下操作:

int* p = malloc( 10 * sizeof( int ) );
/* Take note of the memory size I'm requesting in the 
realloc call compared to yours. */
int* tmp = NULL;
if ( ( tmp = realloc( p, 20 * sizeof( int ) ) ) == NULL ) {
/* We failed to find available memory, but we're 
still on the hook for freeing the memory pointed to by p. */
free( p );
return;
}
/* We were successful in either extending the memory pointed to by p
or a new block of memory was allocated for us and the memory pointed to by p
was copied over for us. In either case, you do not have to free p
before assigning tmp to p. */
p = tmp;

最新更新