views:

157

answers:

2

This is an interview question. If you use malloc to get a piece of memory, such as:

char *p = (char *) malloc (100);

Now you find you need more memory, say 130. How to obtain the memory such that the new piece of memory is still continuous

+9  A: 
ptmp = realloc(p, 130);
if (ptmp == NULL)
    handle_out_memory_condition();
p = ptmp;

Alternately:

p = realloc(p, 130);
if (p == NULL)
    abort();

Note that p may have a new value, depending on whether the contents needed to be moved to find a contiguous block of the new size.

Documentation: http://opengroup.org/onlinepubs/007908775/xsh/realloc.html

Daniel Stutzbach
And if realloc fails you leak the previous 100 bytes `p` pointed to. `realloc` to a temporary variable, test, and if ok assign to the original variable
pmg
`p = realloc(p, 130)` is poor form. You should always store `realloc`'s result in a temporary value first to make sure that it succeeded. Otherwise you risk losing the original pointer and leaking memory.
jamesdlin
@pmg, @jamesdlin: I've updated my answer.
Daniel Stutzbach
It might be worth implementing an `xrealloc` wrapper that takes a pointer to pointer as its argument and modifies that only on success, and simply returns success/failure.
R..
A: 

Appart from all the obvious realloc and malloc answers, if your using MSVC, you can use _expand, which will attempt to resize the block, without moving it

Necrolis
So will realloc(), with a high quality implementation. In other words, nearly always.
Darron
`realloc` will also attempt to resize the block without moving. The difference is how they behave if the block cannot be resized without moving. `_expand` will fail. `realloc` will move it.
Daniel Stutzbach
It's certainly possible that a high quality implementation will allocate blocks of each possible size in their own zone that's exclusively for objects of that particular size, and that in-place resizing will never be possible. Under many workloads, this might be optimal. It could be especially effective with threads since you avoid the lock contention of trying to split/merge free blocks.
R..
@R: Common sizes? Yes. Each possible size? I hope not! ;-)
Daniel Stutzbach