Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update other pointers when realloc moves the memory block?

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?

like image 888
zajcev Avatar asked Jan 31 '10 15:01

zajcev


People also ask

Does realloc change the pointer?

The realloc function changes the size of the block whose address is ptr to be newsize . Since the space after the end of the block may be in use, realloc may find it necessary to copy the block to a new address where more free space is available. The value of realloc is the new address of the block.

Does realloc overwrite memory?

No, the data will be copied for you into the new block that the returned p points at, before the old block is freed.

Does realloc return void pointer?

Return Valuerealloc returns a void pointer to the reallocated (and possibly moved) memory block. If there is not enough available memory to expand the block to the given size, the original block is left unchanged, and NULL is returned.

What happens to old memory after realloc?

If realloc succeeds, it will take ownership of the incoming memory (either manipulating it or free ing it) and return a pointer that can be used ("owned") by the calling function. If realloc fails (returns NULL ), your function retains ownership of the original memory and should free it when it's done with it.


1 Answers

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.

like image 121
t0mm13b Avatar answered Sep 25 '22 02:09

t0mm13b