1

我有一个代码块,它似乎是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;
    }
}
4

7 回答 7

6

malloc 背后的代码肯定比这复杂得多。有几种策略。一种流行的代码是dlmalloc库。K&R 中描述了一种更简单的方法。

于 2009-10-18T01:14:13.077 回答
4

代码显然不完整(并非所有路径都返回值)。但无论如何,这不是一个“真正的”malloc。这可能是尝试实现高度简化的“malloc”“模型”。代码作者选择的方法并不能真正导致有用的实际实现。

(顺便说一句,标准的“malloc”参数的类型为“size_t”,而不是“int”)。

于 2009-10-18T01:18:50.900 回答
2

好吧,该代码中的一个错误是它没有返回指向数据的指针。

我怀疑该代码的最佳方法是[删除]。

于 2009-10-18T01:16:15.320 回答
1

在可能的情况下,我希望 malloc 会尝试将不同的请求放在一起,因为它将有一个可用于 malloc 的代码块,直到它必须获得一个新块。

但是,这也取决于操作系统和硬件架构的要求。如果您只被允许请求某个最小大小的代码,那么每个分配可能不会彼此靠近。

正如其他人提到的,代码片段存在问题。

您可以找到各种具有自己的 malloc 功能的开源项目,最好查看其中一个,以便了解缺少的内容。

于 2009-10-18T01:31:42.370 回答
0

该代码似乎在金属机器上运行,通常在这种仅直接使用物理地址空间的系统上没有虚拟地址映射。

请参阅我的理解,在 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 - > 块吗?你知道,当调用回收时,说 free(void *addr),它也会使用这个地址 -> my_size -> 块算法,在将块返回到堆后相应地更新堆 [块]。

于 2009-10-18T14:01:12.967 回答
0

malloc用于动态分配的内存。这涉及Windows 和/或其他体系结构的sbrkmmap或其他一些系统功能。我不确定您int heap[10000]的用途是什么,因为代码太不完整。

Effo 的版本更有意义,但它引入了另一个黑盒功能get_block,因此并没有太大帮助。

于 2009-10-19T01:01:26.390 回答
0

小到成为一个完整的 malloc 实现

看看 Visual Studio 6.0 的 C 库的源代码,如果我没记错的话,你会在那里找到 malloc 的实现

于 2009-10-19T23:44:26.383 回答