How to update other pointers when realloc moves th

2019-01-19 10:29发布

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?

5条回答
姐就是有狂的资本
2楼-- · 2019-01-19 10:54

Yes, the cptr becomes invalid if realloc moves the block.

查看更多
劫难
3楼-- · 2019-01-19 10:58

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;

查看更多
▲ chillily
4楼-- · 2019-01-19 11:03

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.

查看更多
Evening l夕情丶
5楼-- · 2019-01-19 11:04

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;

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

查看更多
成全新的幸福
6楼-- · 2019-01-19 11:09

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.

查看更多
登录 后发表回答