使用realloc时内存会自动释放吗?或者是否有必要将 free 与 realloc 一起使用?以下哪项是正确的?
//Situation A
ptr1 = realloc(ptr1, 3 * sizeof(int));
//Situation B
ptr1 = realloc(ptr2, 3 * sizeof(int));
free(ptr1);
ptr1 = ptr2;
最佳答案
两者都不正确。 realloc() 可以返回指向新分配内存的指针,或者在错误时返回 NULL。你应该做的是检查返回值:
ptr1 = realloc(ptr2, 3 * sizeof(int));
if (!ptr1) {
/* Do something here to handle the failure */
/* ptr2 is still pointing to allocated memory, so you may need to free(ptr2) here */
}
/* Success! ptr1 is now pointing to allocated memory and ptr2 was deallocated already */
free(ptr1);
关于C - 如果使用 realloc 是 free 必要的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5426700/