realloc移动内存块时如何更新其他指针?
realloc 参考资料说:
该函数可能会移动内存块 到一个新位置,在这种情况下 返回新位置。
这是否意味着如果我这样做:
void foo() {
void* ptr = malloc( 1024 );
unsigned char* cptr = ( unsigned char* )ptr+256;
ptr = realloc( ptr, 4096 );
}
那么如果 realloc 移动块,那么 cptr 可能会变得无效?
如果是,那么 realloc 是否会以任何方式发出信号,表明它将移动该块,以便我可以采取措施防止 cptr 变得无效?
The realloc reference says:
The function may move the memory block
to a new location, in which case the
new location is returned.
Does it mean that if I do this:
void foo() {
void* ptr = malloc( 1024 );
unsigned char* cptr = ( unsigned char* )ptr+256;
ptr = realloc( ptr, 4096 );
}
then cptr may become invalid if realloc moves the block?
If yes, then does realloc signal in any way, that it will move the block, so that I can do something to prevent cptr from becoming invalid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,随着 realloc 移动块,
cptr
将变得无效!不,没有提到向您发出信号告诉您它正在移动内存块。顺便说一句,你的代码看起来很可疑...继续阅读...请参阅我的 回答另一个问题并仔细阅读代码以了解它如何使用realloc
。普遍的共识是,如果您这样做:解决这个问题的方法是使用临时指针并使用它,如下所示:
编辑:谢谢安全 指出了我之前输入此内容时潜入的小精灵。
Yes,
cptr
will become invalid as realloc moves the block! And no, there is no mention of signalling to you to tell that it is moving the block of memory. By the way, your code looks iffy...read on... please see my answer to another question and read the code very carefully on how it usesrealloc
. The general consensus is if you do this:The way to get around that is to use a temporary pointer and use that as shown:
Edit: Thanks Secure for pointing out a gremlin that crept in when I was typing this earlier on.
这来得有点晚了,但是这个问题的解决方案(没有人提到)不是使用指向需要分配的已分配块的指针。相反,使用距基指针的整数值偏移量或(更好)使用 struct 类型和成员元素来寻址分配对象中的特定位置。
This is coming a bit late, but the solution to this problem (which nobody has mentioned) is not to use pointers into allocated blocks that will need to be allocated. Instead, use integer-valued offsets from the base pointer or (better) use a
struct
type and member elements to address specific locations in the allocated object.是的,如果 realloc 移动了块,
cptr
将变得无效。不,没有信号。您必须根据原始
ptr
位置检查返回值。Yes,
cptr
will become invalid if realloc moves the block.No, there is no signal. You would have to check the return value against the original
ptr
location.是的。
最好的办法是比较重新分配前后的 ptr,看看它是否已被移动。您不应该分配指向偏移值的指针,而是应该存储偏移量,然后用它索引原始运算符。
即
代替
void* newPtr = ptr + 10;
*newPtr = some;
使用
int 新 = 10;
ptr[新] = 某事;
Yes.
Best thing to do is compare ptr before and after the reallocation, and see if it has been moved. You shouldn't assign a pointer to the offset value, instead you should store the offset and then index the original operator with it.
i.e.
Instead of
void* newPtr = ptr + 10;
*newPtr = something;
Use
int new = 10;
ptr[new] = something;
是的,如果 realloc 移动了块,则 cptr 会变得无效。
Yes, the cptr becomes invalid if realloc moves the block.