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
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
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
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