Why does a pointer have to be assigned for realloc to work without altering the first value in the memory block?

后端 未结 2 1221
野趣味
野趣味 2021-01-26 22:43
int *ptr;
...
realloc(ptr,++count*sizeof(int));
      or
ptr=realloc(ptr,++count*sizeof(int));

I noticed if I use option number one more than once, the

2条回答
  •  借酒劲吻你
    2021-01-26 23:17

    The actual implementation of realloc is implementation-defined, but typically realloc tries to get more memory in two steps. First, it tries to see whether it can expand the allocated block without having to relocate it in memory. If that succeeds, then realloc doesn't have to move anything in memory and the old pointer is valid.

    However, there might not be space to expand the allocated block to the new size. For example, you could imagine that there's another block of allocated memory right after the currently-allocated block, so it would be impossible to expand the boundary forward. In that case, realloc has to allocate a brand-new piece of memory to store the larger block, and the old pointer will no longer be valid. This is why you should write

    ptr = realloc(ptr, newSize);
    

    instead of

    realloc(ptr, newSize);
    

    Of course, there are other reasons why realloc might move memory around. The memory allocator might have specific size requirements for blocks in different parts of memory, or it might try to optimize performance by compacting memory as it goes. In either case, realloc might move memory around without notice, so you may need to change where ptr points.

    Hope this helps!

提交回复
热议问题