0

new[] doesn't support change the size of allocated memory, does it?

For example, I allocated memory with new[] for buffer (array of char) and I want to get the additional memory.

Should I use malloc/realloc instead in this case?

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
Dmitry
  • 47
  • 4

5 Answers5

4

new does not support that.

You can mimic the behavior of realloc manually using new, delete and memcpy.

By the way, you should always use the same family of methods i.e. either malloc / realloc / free or new / delete, and not mix realloc with new / delete. See for example the FMM errors reported by Purify.

Uraza
  • 556
  • 3
  • 17
2

The closest you can come in standard C++ without resorting to the C holdovers malloc and realloc is to use std::vector<char>. This can be resized at any time, and if the underlying storage gets reallocated the contents will be automatically copied.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Using std::vector instead of the C-string affects the speed? – Dmitry Dec 03 '13 at 17:10
  • 1
    @Dmitry it shouldn't, but if this is important to you you should benchmark it. Different implementations can vary. – Mark Ransom Dec 03 '13 at 17:12
  • ok. And what's the faster, std::vector or std::string you think? – Dmitry Dec 03 '13 at 17:20
  • 2
    @Dmitry: They do pretty much the same thing, so will be about as fast as each other. If you really need to count nanoseconds, then you'll have to time them, or analyse the generated machine code. – Mike Seymour Dec 03 '13 at 17:22
1

Use std::vector. You'll not have to deal with these issues.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
1

It is not a good idea to use malloc/realloc with new.

new will not support reallocating more memory once applied.

So a good idea would be to create a new buffer with extra memory, memcpy and delete the old buffer. Then point to this new buffer.

Akshya11235
  • 959
  • 4
  • 11
  • 25
  • And as Basilevs said, in C++ Vector is always better choics because it has been implemented to automatically resize if need arises. – Akshya11235 Dec 03 '13 at 16:46
0

You should use std::vector instead. It can be resized.

Basilevs
  • 22,440
  • 15
  • 57
  • 102