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?
Yes, the cptr becomes invalid if realloc moves the block.
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;
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.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.
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.