小编use*_*420的帖子

正确使用realloc()

从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)语句吗?

c memory-leaks realloc calloc dynamic-memory-allocation

21
推荐指数
2
解决办法
1万
查看次数