realloc() 的正确使用 [英] Proper usage of realloc()

查看:44
本文介绍了realloc() 的正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 man realloc:realloc() 函数返回一个指向新分配内存的指针,该指针适合任何类型的变量对齐,可能 与 ptr 不同,如果请求失败,则为 NULL.

From man realloc:The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails.

所以在这个代码片段中:

So in this code snippet:

ptr = (int *) malloc(sizeof(int));
ptr1 = (int *) realloc(ptr, count * sizeof(int));
if(ptr1 == NULL){           //reallocated pointer ptr1
    printf("Exiting!!
");
    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) 执行(出于注释中给出的原因)然后内存块将被擦除并且程序将变得疯狂.我应该输入另一个条件来比较 ptr 和 ptr1 的相等性并排除 free(ptr) 语句的执行吗?

Is it sufficient to just assume that the reallocated pointer points to a different block of memeory and not to the same block.Because if the assumption becomes false and realloc returns the address of the original memory block pointed to by ptr and then free(ptr) executes(for the reason given in the comments) then the memory block would be erased and the program would go nuts. Should I put in another condition which will compare the equality of ptr and ptr1 and exclude the execution of the free(ptr) statement?

推荐答案

只是不要在快乐路径中的原始 ptr 上调用 free() .基本上 realloc() 已经为你做到了.

Just don't call free() on your original ptr in the happy path. Essentially realloc() has done that for you.

ptr = malloc(sizeof(int));
ptr1 = realloc(ptr, count * sizeof(int));
if (ptr1 == NULL) // reallocated pointer ptr1
{       
    printf("
Exiting!!");
    free(ptr);
    exit(0);
}
else
{
    ptr = ptr1;           // the reallocation succeeded, we can overwrite our original pointer now
}

这篇关于realloc() 的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆