Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a realloc equivalent in C++?

In C, we have malloc(), free(), and realloc(). In C++ we have new(), delete() and their array versions. Is there a C++ realloc function? I'm implementing some low level stuff in embedded land and just realized there was no realloc function to pair up with the C++ functions and wanted to make sure I wasn't missing anything. I'm guessing "placement new" into a new, separate buffer is the closest match, but wanted to be sure.

Restating the question a bit as I'm getting some answer a bit far afield.

I have implemented device level malloc/new/realloc/etc. functions on my embedded device and wanted to double check to be sure there was no C++ realloc type function that I was unaware of.

like image 967
Michael Dorgan Avatar asked Jun 24 '13 21:06

Michael Dorgan


People also ask

What is the use of realloc in C?

The C library function void *realloc(void *ptr, size_t size) attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc. Declaration. Following is the declaration for realloc() function. Parameters.

What is the use of calloc in C?

Calloc Memory successfully freed. C realloc () method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory.

What is the difference between malloc and free in C++?

The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr); Example:

How to dynamically de-allocate the memory in C?

The elements of the array are: 1, 2, 3, 4, 5, C free () method “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc () and calloc () is not de-allocated on their own.


1 Answers

No, there is no direct equivalent. You would have to do the implementation yourself. Since a class really shouldn't change its size, this isn't really an issue. Move semantics can handle most of these cases.

However, there are some classes that use header info + tail end allocated data. To code these 'properly' you would have to override the operator new() and operator delete() function for the class to handle this additional 'flexible' data. How you 'reallocate' the data is specific to your needs.

If this doesn't answer your question, post an example of what you are attempting.

like image 56
Adrian Avatar answered Oct 15 '22 02:10

Adrian