I am wondering how one would append additional memory to the end of a pointer that already has memory allocated?

For example, if I do something like this...

int *intPtr = new int[5]; // pointer can be assigned 5 values of type int

// Now I want to add more memory to the end of this pointer so that it can hold 3 more ints

// much like a memory-append

How would this be done properly?

I was thinking that I could get away with sending a reference to a pointer to a method and then allocating memory to that location (intPtr[5] ) but I don't know if there are other more secure methods, or if this one is even ideal.

Any ideas?

10 Years
Discussion Span
Last Post by Narue

>I am wondering how one would append additional memory
>to the end of a pointer that already has memory allocated?
Assuming one can't use a container class that handles memory for you, realloc doesn't have a C++ alternative, so you're stuck doing it manually. Here are the steps:

1) Allocate a new block with the larger (or smaller) size.
2) Copy the data you want to keep into the new block.
3) Update any aliases you have pointing to the old block to the new block.
4) Release the memory for the old block.

The code might look like this:

#include <algorithm>
#include <cstddef>
#include <iostream>

namespace JSW {
  template <typename T>
  T *realloc ( T *p, std::size_t old_size, std::size_t new_size )
    T *mem = new T[new_size];
    std::size_t n = ( new_size > old_size ) ? old_size : new_size;

    std::copy ( p, p + n, mem );
    delete[] p;

    return mem;

int main()
  using namespace std;

  int *p = new int[5];

  fill_n ( p, 5, 12 );
  copy ( p, p + 5, ostream_iterator<int> ( cout, " " ) );

  p = JSW::realloc ( p, 5, 10 );

  fill_n ( p + 5, 5, 21 );
  copy ( p, p + 10, ostream_iterator<int> ( cout, " " ) );

  delete[] p;
Votes + Comments
Thank you Narue
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.