开发者

After malloc, how to obtain more memory that is still continuous?

开发者 https://www.devze.com 2023-01-19 11:38 出处:网络
This is an interview question. If you use malloc to get a piece of memory, such as: char *p = (char *) malloc (100);

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号