Alex Rivera | Logout

realloc without freeing old memory

Asked 2012-12-18T15:53:18.490
9

I want to use realloc to increase memory size while keeping the pointer unchanged (because the callers uses it). realloc does not always do that; sometimes it returns a different pointer and frees the old one. I would like to "try" to realloc memory and if it is not possible, fallback to a different method using the original pointer - but realloc has already destroyed that!

Is there a way to try to increase malloc'ed memory without destroying (as realloc does) the old pointer if it is not possible?

E.g.

void *pold;
void *pnew = realloc(pold, newsize);
if (pnew != pold)
{
     free(pnew);
     DoDifferently(pold); // but pold is freed already
}

P.S. I don't care about portability (linux only, thus the tag).

Edit
Report

2 Answers

1

I don't think there's a portable realloc-type function that would do this.

One relatively easy portable solution is to pre-allocate a larger block of memory than you need initially. That'll allow for some growth without changing the pointer (in effect, you'll be doing your own in situ realloc).

Once you exceed the original block, you'll have to allocate a new one in its stead. This is your "failure" scenario.

answered 2012-12-18T15:58:51.067
1

There is no portable solution to this problem, and the non-portable solution is not free from risk.

The non-portable solution, which works with GNU malloc, is to use malloc_usable_size to find out how big the memory region actually is. However, even if the memory region is big enough, I'm not sure if realloc is not guaranteed to use it. IIRC, there used to be an option which caused realloc to always allocate new memory, but I can't find it any more; I didn't look very hard, though.

answered 2012-12-18T16:05:03.370

Your Answer