Gary Allen
Gary Allen

Reputation: 1380

Alternative to realloc() in C++?

In C, we can simply use realloc() to increase/decrease the size of memory a pointer is pointing to.

Is there an equivalent reallocation operator/function in C++ in the context of having used "new" to initially allocate the memory?

Upvotes: 3

Views: 1065

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

No, there is no renew call :-)

And, to be honest, with all the rich (and auto-sizing) data structures provided by C++, there's little need for it. For example, while C strings might need to be resized to add more text, std::string just takes care of it for you. As does std::vector for other arrays, and so on.

If you really wanted to go against the last twenty years of improvement in C++ and do that, you can always revert to the C way (since malloc, free and realloc are available), but I'd suggest not doing that if you can avoid it.

You could also try to implement a renew feature but it's going to be slightly harder as you won't have access to internal memory allocation data (as realloc does). That means every renew is probably going to be an "allocate and copy" operation.

And, if you provide a class that can give you that information, you're already into the "slightly more complex than a byte array" arena, so would probably just step up to letting the class itself do the heavy lifting of reallocation.


As an aside, I've never really been that fond of realloc since, if it fails, you've generally lost the old pointer in a memory leak. That means I've always had to do things like:

int betterReAlloc(void **pOldPtr, size_t newSz) {
    void *newptr = realloc(*pOldPtr, newSz);
    if (newPtr != NULL) *pOldPtr = newPtr)
    return newptr != NULL;
}

char *ptr = somethingValidlyMalloced();
if (! betterReAlloc(&ptr, BETTER_SIZE)) {
    puts("Cannot realloc, using original");
}

Upvotes: 3

Related Questions