0

So in C++, I read that C realloc(&dest, &source, nbytes) is bad because it doesn't work with new and delete.

So how to reallocate data correctly in C++? Assume I have:

int* a = new int[100];

But I wish to resize it to int[200]. The simplest way I think of is:

int* old = a;
int* newPos = new int[200];
memcpy(newPos, a, sizeof(int)*100);
a = newPos;
delete[] old;

Is there a simpler way? Thank you

Duke Le
  • 332
  • 3
  • 14
  • 1
    Use [C++ containers](https://en.cppreference.com/w/cpp/container), probably `std::vector`, in your case `std::vector` – Basile Starynkevitch Dec 14 '19 at 06:50
  • Yes I know that containers are correct in this case. But specifically, is there anyway to realloc in C++? – Duke Le Dec 14 '19 at 06:57
  • 5
    Does this answer your question? [Reallocating memory of a C++ array.](https://stackoverflow.com/questions/9586345/reallocating-memory-of-a-c-array) – Raj Dec 14 '19 at 06:59
  • 1
    And the *compiler* usually knows about standard containers. BTW, even in C, `realloc` is often incorrectly used (e.g. for failure cases). So please use containers, or give up C++ – Basile Starynkevitch Dec 14 '19 at 07:00

1 Answers1

2

You should use std::copy, not memcpy:

std::copy(old, old+100, newPos);

but in general, you should avoid using new and delete directly and instead use standard containers (probably std::vector<int> in your case) which deal with all of this for you when you call their resize method.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226