Search code examples
cmemorymallocrealloc

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?


Solution

  • 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.