如何malloc的作品? [英] How malloc works?

查看:147
本文介绍了如何malloc的作品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  如何用C做免费和malloc的工作?

考虑一个场景,我必须通过的malloc分配大约20字节的内存。为函数调用的malloc()是成功的,应在20个字节可用连续存储器或可以将它分散?对于例如,在上述情况下,如果有的每10个字节4或5块,将MALLOC工作?或者是这个操作系统的特定的或编译器特定的?

Consider a scenario where i have to allocate some 20 bytes of memory through malloc. For the function call to malloc() to be successful, should the 20 bytes be available contiguously in memory or can it be scattered? For eg, in the above case, if there are 4 or 5 chunks of 10 bytes each, will malloc work? Or is this OS specific or compiler-specific?

推荐答案

现在的问题是一种错误。

The question is kind of wrong.

在一个典型的OS,存在虚拟存储器和物理存储器的概念。

In a typical OS, there exists the concepts of virtual memory and physical memory.

物理内存通常在4KB块同样存在,虚拟内存。

Physical memory exists typically in 4kb blocks, virtual memory likewise.

每个进程都有虚拟内存 - 给每个进程似乎是完全可寻址内存范围操作系统presents。因此,在32位计算机上,每个进程'认为'它具有4 GB内存contigious的。

Each process has virtual memory - to each process the OS presents what appears to be the fully addressable memory range. So on a 32 bit machine, each process 'thinks' it has 4 GB of contigious memory.

在现实中,OS,在幕后,忙映射虚拟内存分配到物理内存的实际块。因此,比方说,400KB虚拟存储器分配,被映射到100个物理块。这些物理块不必是contigious(几乎从未是 - 没有什么情况发生停止,但一台机器做任何工作的,这是极不可能的),但虚拟内存分配的确实的需要是contigious。

In reality, the OS, behind the scenes, is busy mapping virtual memory allocations onto real blocks of physical memory. So a, say, 400kb virtual memory allocation, is mapped onto 100 physical blocks. Those physical blocks do not need to be contigious (and almost never are - nothing stops it from happening, but on a machine doing any kind of work, it's highly improbable) but the virtual memory allocation does need to be contigious.

所以,你仍然可以运行到虚拟内存碎片。这里,一个进程请求的内存块,并没有,在该特定过程虚拟存储器映射,的contigious虚拟存储器块,使得请求能够得到满足。

So you can still run into virtual memory fragmentation. Here, a process requests a block of memory and there isn't, in that particular processes virtual memory map, a block of contigious virtual memory such that the request can be satisfied.

这问题是你在想的问题。

That problem is the problem you're thinking of.

这篇关于如何malloc的作品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆