如何更新其他指针时realloc的移动内存块? [英] How to update other pointers when realloc moves the memory block?

查看:131
本文介绍了如何更新其他指针时realloc的移动内存块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该realloc的基准说:

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 );
}

然后CPTR可能,如果移动的realloc块失效了?

then cptr may become invalid if realloc moves the block?

如果是的话,确实realloc的信号,以任何方式,它将移动块,这样我可以成为做一些prevent CPTR无效?

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?

推荐答案

CPTR 作为realloc的移动模块将成为无效!没有,没有任何信号给你,告诉它移动的内存块的提及。顺便说一句,你的code看起来前途未卜......阅读...请看我的answer另外一个问题,非常仔细阅读code。关于它如何使用的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 uses realloc. The general consensus is if you do this:


void *ptr = malloc(1024);

/* later on in the code */

ptr = realloc(ptr, 4096);

/* BAM! if realloc failed, your precious memory is stuffed! */

来解决该问题的方法是使用一个暂时指针,并使用该所示:

The way to get around that is to use a temporary pointer and use that as shown:


void *ptr = malloc(1024);

/* later on in the code */

void *tmp = realloc(ptr, 4096);

if (tmp != null) ptr = tmp;

编辑:感谢 安全您指出,当我输入这个早些时候就蹑手蹑脚一小鬼

Thanks Secure for pointing out a gremlin that crept in when I was typing this earlier on.

这篇关于如何更新其他指针时realloc的移动内存块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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