How to expand allocated memory in place

旧街凉风 提交于 2020-12-05 20:05:31

问题


Is there something like std::realloc but do nothing if it fails to expand the existing memory (of course it will let you know it failed)?

I mean truly expand in place. Not copy to a newly created memory chunk.


回答1:


Contrary to what other answers say, the function you need could be provided by the C standard ibrary. It isn't for some reason or other.

It was considered for an adition to the C standard, see e.g. http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1527.pdf (search for try_realloc). I don't know if the C committee is still pursuing this.

Bottom line, there's no such function as of now.




回答2:


No, there is no such function.

From your comments, I suppose that the following might be of interest to you: `std::realloc` for non-POD types and What is C++ version of realloc(), to allocate the new buffer and copy the contents from the old one?


PS: Re-approach your problem, since the existing methology is most usually enough.




回答3:


truly expand in place. Not copy to a newly created memory chunk.

This is impossible because of how virtual address space works on direct-addressing (non-segmented) instruction set architectures like x86-64 (or ARM, MIPS, RISCV, etc....).

(so that strong limitation is mostly not from software, but from your hardware, in the previous century some segmented architectures like iAPX432 or Rekursiv have been proposed, but failed)

Let's suppose you want to realloc a pointer zone of one megabytes to get four megabytes of more memory. But the virtual address space of your process could contain some other data -for some other malloc-ed zone or something else like a code segment, a call stack, etc...- used two megabytes ahead. So you need to move your (growing) zone -by asking your OS for some fresh 4 megabyte zone- and copy from the previous one.

On Linux, look into proc(5) (e.g. type man 5 proc in a terminal) and into mmap(2). Run the cat /proc/self/maps and cat /proc/$$/maps commands in some terminal to get a better intuition about virtual address space. Be aware that all memory management is done above such mmap and related (sometimes, old sbrk) system calls. So your malloc or operator new is (sometimes) using them (most of the time, reusing previously free-d zone is preferable). Use strace(1) to explore the system calls done by existing programs.

BTW, on Linux, both your C standard library and your C++ standard library are free software. You could study their source code.

Read also Operating Systems: Three Easy Pieces to understand more how OSes work. Consider reading some book on Computer Architecture (or at least some slides on the simplified Y86 architecture). You've got some deep misunderstanding about how your computer works.



来源:https://stackoverflow.com/questions/47645086/how-to-expand-allocated-memory-in-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!