C - 如果使用 realloc 是 free 必要的吗?

标签 c pointers

使用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/

相关文章:

c - 用于文件传输的选择性重复协议(protocol)

c - 如何在循环中实例化新的结构实例

关于C中指针递减的困惑

字符内存分配

c - 复制 int 片段后的相等性检查

c - 从文件中读取一行并打印

c++ - C/C++结构不完整成员类型不一致?

c - 如何在c中读取由 ":"分隔的两个字符串

c++ - 为什么我得到输出空白?

C - 释放数组内的指针