用C的malloc代码
-
21-09-2019 - |
题
我有一个代码块,这似乎是后面malloc
的代码。但是,当我通过代码,我得到的代码的某些部分丢失的感觉。没有人知道,如果有是缺少的功能的一部分?是否malloc
总是相邻块结合在一起?
int heap[10000];
void* malloc(int size) {
int sz = (size + 3) / 4;
int chunk = 0;
if(heap[chunk] > sz) {
int my_size = heap[chunk];
if (my_size < 0) {
my_size = -my_size
}
chunk = chunk + my_size + 2;
if (chunk == heap_size) {
return 0;
}
}
解决方案
后面的malloc代码是肯定比这更加复杂。有几种策略。一种流行的代码是 dlmalloc 库。一个更简单的一个是在K&R说明。
其他提示
代码显然是不完整的(不是所有的路径返回的值)。但无论如何,这不是一个“真正”的malloc。这可能是实现“的malloc”的一个高度简化的“模型”的一种尝试。由代码的作者选择的方法不能真正导致一种有用的实际实现。
(和顺便说一句,标准“的malloc的参数具有类型 '为size_t',而不是 'INT')。
那么,在这种代码的一个错误是,它不返回一个指针的数据。
我怀疑该代码最好的方法是[删除]。
如果可能的话,我希望的malloc会尽量把不同的请求彼此接近,因为这将有一个代码块,可用于的malloc,直到它必须找一个新块。
但是,这也依赖于由操作系统和硬件体系结构提出的要求。如果只允许请求的代码具有一定的最小尺寸那么它可以是每个分配将不会被彼此接近。
正如其他提到的,有与所述代码段的问题。
您可以找到有自己的malloc函数的各种开源项目,它可能是最好看的一个,为了得到一个想法是错过了什么。
malloc
为动态分配存储器。这就涉及sbrk
,mmap
,或者一些其它系统功能为Windows和/或其它架构。我不知道你是int heap[10000]
什么,因为代码是太不完整的。
Effo的版本做一点点的感觉,但随后介绍另一个黑匣子功能get_block
,所以没有太大的帮助。
代码似乎是一个金属的机器上运行,这样的系统仅直接使用的物理地址空间上通常没有虚拟地址的映射。
请参阅一个32位的系统上我的理解,的sizeof(PTR)= 4字节:
extern block_t *block_head; // the real heap, and its address
// is >= 0x80000000, see below "my_size < 0"
extern void *get_block(int index); // get a block from the heap
// (lead by block_head)
int heap[10000]; // just the indicators, not the real heap
void* malloc(int size)
{
int sz = (size + 3) / 4; // make the size aligns with 4 bytes,
// you know, allocated size would be aligned.
int chunk = 0; // the first check point
if(heap[chunk] > sz) { // the value is either a valid free-block size
// which meets my requirement, or an
// address of an allocated block
int my_size = heap[chunk]; // verify size or address
if (my_size < 0) { // it is an address, say a 32-bit value which
// is >0x8000...., not a size.
my_size = -my_size // the algo, convert it
}
chunk = chunk + my_size + 2; // the algo too, get available
// block index
if (chunk == heap_size) { // no free chunks left
return NULL; // Out of Memory
}
void *block = get_block(chunk);
heap[chunk] = (int)block;
return block;
}
// my blocks is too small initially, none of the blocks
// will meet the requirement
return NULL;
}
编辑:有人能帮忙解释算法中,也就是转换地址 - > my_size - >块?你知道,当呼叫不退,说免费(void *的地址),它会使用这个地址 - > my_size - >块算法中也更新堆[块因此该块返回到堆后
要小,为一个整体的malloc实施
以在Visual Studio 6.0的C库的来源看,在那里你会找到的malloc执行,如果我没有记错的话