3

Possible Duplicate:
How do you realloc in C++?

I know that C++ arrays can be reallocated (expanded) using realloc() if memory has been allocated via malloc() or calloc(). My question is, how can I expand an array in C++ whose memory has been allocated via the new operator?

Community
  • 1
  • 1
Amal Antony
  • 6,477
  • 14
  • 53
  • 76
  • malloc/realloc are C library calls - although they can be used in C++ they should in general be avoided since C++ has more robust ways of dealing with dynamic arrays etc. – Paul R Mar 06 '12 at 15:17

3 Answers3

12

You can't - that's why in C++ you use std::vector<>.

If you wanted to do this, you'd have to allocate a new array (via new), then copy the old items across (std::copy for example), then delete[] the previous array.

Just use std::vector - let it do all that stuff for you...

Nim
  • 33,299
  • 2
  • 62
  • 101
6

In general C++ arrays cannot be reallocated with realloc, even if the storage was allocated with malloc. malloc doesn't give you arrays. It gives pointers to usable storage. There's a subtle difference here.

For POD types, there's little difference between usable storage and actual objects. But for non-POD types, usable storage and objects are totally different things.

realloc gives you a larger portion of usable storage. It manipulates storage not objects. That may work fine for POD types, but for other types it's a recipe for disaster.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • So technically is it possible to expand an array using `realloc()` that was allocated using `calloc()` or is `realloc()` possible only if memory has been allocated via `malloc()` ? – Amal Antony Mar 06 '12 at 15:35
  • @amalantony Oh, the same goes for `calloc`. The problem is with `realloc` itself. It doesn't care for objects, only storage. – R. Martinho Fernandes Mar 06 '12 at 15:37
  • 1
    @amal: the difference between `malloc` and `calloc` is completely irrelevant to what Martinho is saying here. You can't `realloc` non-POD objects, because you can't copy them byte-by-byte, and that's all `realloc` is defined to do. Even in C, if your objects contain pointers into themselves or each other then you can't `realloc` them because the addresses would no longer be correct. C++ just adds the caveat that for non-POD classes, the implementation might insert things like that of its own accord. – Steve Jessop Mar 06 '12 at 15:37
0

Use ::std::vector.

Take a look at this question or this question for more details.

Community
  • 1
  • 1
Daniel Rose
  • 17,233
  • 9
  • 65
  • 88