How to update other pointers when realloc moves th

2019-01-19 10:15发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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;



回答5:

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