0

Is it possible to reallocate more space only if the address stays the same? Like a type of realloc that fails if it cannot do that and would have to return a new address.

While putting final optimizing touches on my specialized pod container, using realloc does yield a reasonable performance boost in my testing but I cannot invalidate pointers to the data during the lifetime of the container and thus cannot leave this up to chance and good luck.

user81993
  • 6,167
  • 6
  • 32
  • 64
  • 2
    Being forced to fail if realloc moves the vector sounds like a design problem. What's the point of using dynamic allocation if you have to decide in advance how big the final allocation will be? But anyway, nothing stops you from comparing the old pointer with the one returned by realloc, and then failing if they differ. – rici Oct 14 '20 at 00:35
  • 5
    "*nothing stops you from comparing the old pointer with the one returned by realloc, and then failing if they differ*" - if `realloc()` decides to allocate new memory elsewhere, the existing data is moved and the old pointer is invalidated. There is no opportunity for the caller to check for a difference and fail gracefully since the damage has already been done before `realloc()` exits. The OP doesn't want invalidation to happen, and that is simply not doable with `realloc()`. – Remy Lebeau Oct 14 '20 at 00:38
  • 3
    If you're using MS and don't mind non-portability, you can use `_expand`. https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/expand?view=vs-2019 – L. Scott Johnson Oct 14 '20 at 00:43
  • I have [a malloc implementation](https://github.com/ChrisDodd/shm_malloc) that has an `mresize` function that does exactly what you want. The package is primarily designed for efficient parallel shared memory allocation, but it can be used as a drop-in malloc replacement. – Chris Dodd Oct 14 '20 at 04:37

1 Answers1

0

This is generally not feasible in a dynamic memory allocation scheme. An allocator could guarantee memory at the same address would be available only by reserving as much memory as might ever be required at that address to start with. If it does not reserve that much memory for allocation A, then some subsequent allocation B may be placed at some place after A earlier than that maximum potential reservation, and then A could never be enlarged beyond B, since B would be in the way.

One possible way this might be implemented is in a huge address space where each allocation could be given all the virtual address space it might ever need but have physical memory mapped only for the space that has been currently requested. An implementation-dependent custom allocator could be implemented for that.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Its fine if I cannot reallocate beyond B, I just want to get as much as I can and if I can't get any more I'll just hop somewhere else for the subsequent data. – user81993 Oct 14 '20 at 00:48