use*_*420 21 c memory-leaks realloc calloc dynamic-memory-allocation
从man realloc:realloc()函数返回一个指向新分配的内存的指针,该内存适用于任何类型的变量,可能与ptr不同,如果请求失败则为NULL.
所以在这段代码中:
ptr = (int *) malloc(sizeof(int));
ptr1 = (int *) realloc(ptr, count * sizeof(int));
if(ptr1 == NULL){ //reallocated pointer ptr1
printf("Exiting!!\n");
free(ptr);
exit(0);
}else{
free(ptr); //to deallocate the previous memory block pointed by ptr so as not to leave orphaned blocks of memory when ptr=ptr1 executes and ptr moves on to another block
ptr = ptr1; //deallocation using free has been done assuming that ptr and ptr1 do not point to the same address
}
Run Code Online (Sandbox Code Playgroud)
仅仅假设重新分配的指针指向不同的记忆块而不是同一个块就足够了.因为如果假设变为false并且realloc返回ptr指向的原始内存块的地址然后free(ptr)执行(由于评论中给出的原因)然后内存块将被删除,程序将疯狂.我应该放入另一个条件来比较ptr和ptr1的相等性并排除执行free(ptr)语句吗?
Aar*_*and 23
只是不要free()
在快乐的道路上打电话给你原来的ptr.基本上realloc()
已经为你完成了.
ptr = malloc(sizeof(int));
ptr1 = realloc(ptr, count * sizeof(int));
if (ptr1 == NULL) // reallocated pointer ptr1
{
printf("\nExiting!!");
free(ptr);
exit(0);
}
else
{
ptr = ptr1; // the reallocation succeeded, we can overwrite our original pointer now
}
Run Code Online (Sandbox Code Playgroud)
根据下面的好评,将修复应用为编辑。
阅读这个 comp.lang.c 问题,揭示了 3 种情况:
realloc
根本找不到足够的空间,它会返回一个空指针,并保留先前分配的区域。”这可以直接转换为代码:
int* ptr = (int*)malloc(sizeof(int));
int* tmp = (int*)realloc(ptr, count * sizeof(int));
if(tmp == NULL)
{
// Case 3, clean up then terminate.
free(ptr);
exit(0);
}
else if(tmp == ptr)
{
// Case 1: They point to the same place, so technically we can get away with
// doing nothing.
// Just to be safe, I'll assign NULL to tmp to avoid a dangling pointer.
tmp = NULL;
}
else
{
// Case 2: Now tmp is a different chunk of memory.
ptr = tmp;
tmp = NULL;
}
Run Code Online (Sandbox Code Playgroud)
因此,如果您考虑一下,您发布的代码很好(几乎)。上面的代码简化为:
int* ptr = (int*)malloc(sizeof(int));
int* tmp = (int*)realloc(ptr, count * sizeof(int));
if(tmp == NULL)
{
// Case 3.
free(ptr);
exit(0);
}
else if(ptr != tmp)
{
ptr = tmp;
}
// Eliminate dangling pointer.
tmp = NULL;
Run Code Online (Sandbox Code Playgroud)
请注意额外的else if(ptr != tmp)
,它不包括案例 1,您不想调用,free(ptr)
因为ptr
和tmp
引用相同的位置。此外,为了安全起见,我确保分配NULL
totmp
以避免tmp
在范围内出现任何悬空指针问题。
归档时间: |
|
查看次数: |
14565 次 |
最近记录: |