使用realloc时内存是否自动释放?或者是否有必要免费使用realloc?以下哪项是正确的?
//Situation A
ptr1 = realloc(ptr1, 3 * sizeof(int));
//Situation B
ptr1 = realloc(ptr2, 3 * sizeof(int));
free(ptr1);
ptr1 = ptr2;
Run Code Online (Sandbox Code Playgroud)
小智 41
两者都不正确.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);
Run Code Online (Sandbox Code Playgroud)
Eri*_*rik 10
ptr1 = realloc(ptr2, 3 * sizeof(int));ptr2无效后不应使用.你ptr1只需要免费.在某些情况下,返回值realloc将与您传入的值相同.
您可以安全地认为ptr1=realloc(ptr2, ...与此等效:
ptr1 = malloc(...);
memcpy(ptr1, ptr2, ...);
free(ptr2);
Run Code Online (Sandbox Code Playgroud)
这是大多数情况下发生的情况,除非新的大小仍然适合旧的内存块 - 然后realloc可以返回原始内存块.
与其他分配函数一样,realloc如果失败则返回NULL - 您可能想要检查它.
| 归档时间: |
|
| 查看次数: |
20917 次 |
| 最近记录: |