Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you 'realloc' in C++?

How can I realloc in C++? It seems to be missing from the language - there is new and delete but not resize!

I need it because as my program reads more data, I need to reallocate the buffer to hold it. I don't think deleteing the old pointer and newing a new, bigger one, is the right option.

like image 710
bodacydo Avatar asked Aug 14 '10 10:08

bodacydo


2 Answers

Use ::std::vector!

Type* t = (Type*)malloc(sizeof(Type)*n)  memset(t, 0, sizeof(Type)*m) 

becomes

::std::vector<Type> t(n, 0); 

Then

t = (Type*)realloc(t, sizeof(Type) * n2); 

becomes

t.resize(n2); 

If you want to pass pointer into function, instead of

Foo(t) 

use

Foo(&t[0]) 

It is absolutely correct C++ code, because vector is a smart C-array.

like image 106
f0b0s Avatar answered Sep 22 '22 17:09

f0b0s


The right option is probably to use a container that does the work for you, like std::vector.

new and delete cannot resize, because they allocate just enough memory to hold an object of the given type. The size of a given type will never change. There are new[] and delete[] but there's hardly ever a reason to use them.

What realloc does in C is likely to be just a malloc, memcpy and free, anyway, although memory managers are allowed to do something clever if there is enough contiguous free memory available.

like image 20
Thomas Avatar answered Sep 22 '22 17:09

Thomas