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

后端 未结 5 711
既然无缘
既然无缘 2020-12-10 11:41

The realloc reference says:

The function may move the memory block to a new location, in which case the new location is returned.

相关标签:
5条回答
  • 2020-12-10 12:15

    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.

    0 讨论(0)
  • 2020-12-10 12:21

    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.

    0 讨论(0)
  • 2020-12-10 12:22

    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;

    0 讨论(0)
  • 2020-12-10 12:27

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

    0 讨论(0)
  • 2020-12-10 12:30

    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.

    0 讨论(0)
提交回复
热议问题