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?

Recommended Answers

All 3 Replies

Use a vector instead?

I figured someone would say that!

Oh well, looks like it would be better to learn the containers than reinvent the wheel. Thanks for the suggestion.

>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, " " ) );
  cout<<'\n';

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

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

  delete[] p;
}
commented: Thank you Narue +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.