我想出了如何编写realloc,但我知道代码不对吗?

时间:2009-10-29 00:59:14

标签: c malloc

我决定做的是

  • 致电malloc
  • 将旧块复制到新块
  • 释放旧街区
  • 并将指针返回到新块

下面的代码是我到目前为止的...但我知道这是不对的...任何有关修复代码的帮助都将非常感谢......

如果您需要的代码多于我提供的代码,我会在此之前发布一个显示所有代码的帖子。我是新人所以只有这篇文章和我做过的最后一篇文章。 谢谢。

void *mm_realloc(void *ptr, size_t size)
{
int i, p = *ptr;

 // make a call to malloc to find space
 //allocate memory

 ptr = malloc(size_t*sizeof(int));

 //copying old block to new block
 if(ptr!=NULL)
     for(i=0 ; i<size_t ; i++) 
     {
     *(ptr+i) = i;
     }

//freeing old block
free(ptr);

//return pointer to new block
return *ptr;
}

3 个答案:

答案 0 :(得分:2)

理想情况下,realloc()只会查看当前块之外是否有足够的可用内存,如果是,只需调整竞技场数据结构即可就地扩展当前块。这消除了昂贵的复制操作并降低了分配失败的可能性。这是为了增加尺寸。为了减少,您应该能够始终就地执行此操作,将当前块的其余部分发送回空闲池。

通过执行malloc / free,如果在竞技场中有100K分配了一个60K块,则调用mm_realloc将大小调整为50K将失败。

但是,这是一个可行的解决方案,至少在第一次尝试时,所以这是我实现它的方式:

void *mm_realloc (void *ptr, size_t size) {
    int minsize;
    void *newptr;

    // Allocate new block, returning NULL if not possible.

    newptr = malloc (size);
    if (newptr == NULL) return NULL;

    // Don't copy/free original block if it was NULL.

    if (ptr != NULL) {
        // Get size to copy - mm_getsize must give you the size of the current block.
        // But, if new size is smaller, only copy that much. Many implementations
        // actually reserve the 16 bytes in front of the memory to store this info, e.g.,
        // +--------+--------------------------------+
        // | Header | Your data                      |
        // +--------+--------------------------------+
        //           ^
        //           +--- this is your pointer.
        // <- This is the memory actually allocated ->

        minsize = mm_getsize (ptr);
        if (size < minsize)
           minsize = size;

        // Copy the memory, free the old block and return the new block.

        memcpy (newptr, ptr, minsize);
        free (ptr)
    }

    return newptr;
}

你会注意到你遗失的一件事是它必须只复制旧块和新块的最小的足够字节。否则,您可能会因为其中一个溢出而导致核心转储。

另外,你的循环实际上并没有复制数据,它将块的每个字节设置为它的偏移量,并且在分配新的指针时丢失旧的指针,因此我使用newptr来保持他们分开了。

答案 1 :(得分:1)

您需要知道旧块的大小以及新大小。您必须在新块上复制两种尺寸中较小的一种。

如果malloc()失败,你还必须确保不破坏(释放)旧块 - 你只需返回0。

您也不需要在malloc()中将大小乘以'sizeof(int)';你真的要分配4倍或更多(理论上,它可能只是2倍,但现在很少有人使用16位编译器。)

答案 2 :(得分:1)

realloc的意思是,如果可能的话,它会尝试合并内存块和后面的空闲块。只有在没有空闲的情况下,它才会分配新内存,复制所有内容,并释放旧块。

为什么要编写自己的分配例程呢?

相关问题