【发布时间】:2014-01-27 04:56:54
【问题描述】:
来自 man realloc:realloc() 函数返回一个指向新分配内存的指针,该指针针对任何类型的变量进行适当对齐,并且可能不同于 ptr,如果请求失败,则为 NULL .
所以在这段代码中sn-p:
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
}
仅仅假设重新分配的指针指向不同的内存块而不是同一个块就足够了。因为如果假设变为错误并且realloc返回ptr指向的原始内存块的地址然后释放(ptr) 执行(由于 cmets 中给出的原因)然后内存块将被擦除并且程序会发疯。 我应该输入另一个条件来比较 ptr 和 ptr1 的相等性并排除 free(ptr) 语句的执行吗?
【问题讨论】:
-
PS-我没有足够的代表点来在关于 SO 的另一个类似问题中提出这个问题,所以我不得不提出一个新问题..
标签: c memory-leaks dynamic-memory-allocation realloc calloc