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

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

问题描述

从人的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.

因此​​,在这个code片断:

So in this code snippet:

ptr=(int*)malloc(sizeof(int));
ptr1=(int*)realloc(ptr,count*sizeof(int));
if(ptr1==NULL)          //reallocated pointer ptr1
{       
    printf("\nExiting!!");
    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                     
}

是否足以只是假设重新分配的指针指向memeory不同的块,而不是同一block.Because如果假设为假和realloc返回原来的内存块的地址由ptr,然后免费指出, (PTR)执行(在评论中给出的原因),那么内存块将被删除,程序会去坚果。
我应该把其中将比较PTR和ptr1的平等和排除免费(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=(int*)malloc(sizeof(int));
ptr1=(int*)realloc(ptr,count*sizeof(int));
if(ptr1==NULL)          //reallocated pointer ptr1
{       
    printf("\nExiting!!");
    free(ptr);
    exit(0);
}
else
{
    ptr=ptr1;           // th reallocation succeeded, we can overwrite our original pointer now
}

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

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