tags:

views:

204

answers:

4

Is it possible to incrementally increase the amount of allocated memory on a free store that a pointer points to? For example, I know that this is possible.

char* p = new char; // allocates one char to free store
char* p = new char[10]; // allocates 10 chars to free store

but what if I wanted to do something like increase the amount of memory that a pointer points to. Something like...

char input;
char*p = 0;
while(cin >> input)  // store input chars into an array in the free store
    char* p = new char(input);

obviously this will just make p point to the new input allocated, but hopefully you understand that the objective is to add a new char allocation to the address that p points to, and store the latest input there. Is this possible? Or am I just stuck with allocating a set number.

+1  A: 

realloc

palindrom
+4  A: 

The C solution is to use malloc instead of new -- this makes realloc available. The C++ solution is to use std::vector and other nice containers that take care of these low-level problems and let you work at a much higher, much nicer level of abstraction!-)

Alex Martelli
I'm learning about pointers and about how these low-level concepts work.
trikker
Then it's more of a C than a C++ question (though C++ lets you mess with pointers too, of course, it provides excellent alternatives;-).
Alex Martelli
+1  A: 

You can do this using the function realloc(), though that may only work for memory allocated with malloc() rather than "new"

having said that, you probably don't want to allocate more memory a byte at a time. For efficiency's sake you should allocate in blocks substantially larger than a single byte and keep track of how much you've actually used.

Mark Bessey
Yeah I guess when working at this low level without fancy containers, you can't expect to have the same amenities. I just allocated a set number of blocks and used a counter to keep track of and store data in them. This is what I was planning on in the first place, but I prefer only having as much as I need.
trikker
+1  A: 

You appear to be using C++. While you can use realloc, C++ makes it possible to avoid explict memory management, which is safer, easier, and likely more efficient than doing it yourself.

In your example, you want to use std::vector as a container class for chars. std::vector will automatically grow as needed.

In fact, in your case you could use a std::istreambuf_iterator and std:push_back to std::copy the input into a std::vector.

tpdi