内存分配器 - 遍历内存时出现问题

时间:2016-05-20 17:11:14

标签: c memory memory-management malloc dynamic-memory-allocation

我编写了简单的内存分配器,我遇到了问题,因为我不认为我正在考虑访问内存元素:)我无法找出错误。从输出方面再出现两个问题,还有更多我不会意识到的问题。

问题 - 1)while(block-> next!= NULL)在到达下一个块时崩溃 2)在自由memptr->尺寸中出现零。

我还没有尝试调查内存对齐或碎片方面,目标是让一些简单的工作

#include <stdio.h>
#include <stdbool.h>

#define length 10000

char memory[length] = {0};

typedef struct MEMBLOCK
{
  struct MEMBLOCK *next;
  int size;   
  bool is_available;
}memblock;

int remain_memory = length;

memblock* ptrlastblock;
memblock* endOfBlock(memblock *block);
void* allocMemory(memblock *block, int size);
void* xmalloc(size_t size);
void myfree(void *ptr);


int main(void) 
{
  int *ptr = (int *)xmalloc(10);
  if (ptr == NULL)
  {
    printf("memory allocation failed \n");
  }
  else
  {
    *ptr = 4;
  }
 // myfree(ptr);
  int *ptr1 = (int *)xmalloc(10);
  myfree(ptr1);

  return 0;
}

void* xmalloc(size_t size)
{
  memblock *block = (memblock*) memory;  // point to head of memory region
  return allocMemory(block, size);
}

void* allocMemory(memblock *block, int size)
{
  if (remain_memory == length)  // if no memory used allocate block
  {
    block->next = NULL;            
    block->is_available = false;
    block->size = size;
    ptrlastblock = endOfBlock(block); // point it to beginning of next block
    remain_memory -= size;
    return (void *)block + 1;  // increment block so pointing to begining of memory post block
  }

  if(remain_memory > size)
  {
      while(block->next != NULL)  // keep incrementing till you find 
      {                             // last used chunk
       block = block->next;
      }
    block = endOfBlock(block);
    block->next = NULL;
    block->size = size;
    block->is_available = false;
    remain_memory -= size;
    return (void *)block + 1;
  }
  else
  {
    return NULL;
  }

}

memblock* endOfBlock(memblock *block)
{
  memblock* eofblock = (memblock*)((size_t)(block + 1) + (size_t)block->size);
  return eofblock;
}

void myfree(void *ptr)
{
  memblock *memptr = (memblock *)ptr - 1;
  if (memptr->is_available == false)
  {
    memptr->is_available = true;
    printf(" memory with pointer is %d \n", memptr->size);
    remain_memory += memptr->size;
  }
}

1 个答案:

答案 0 :(得分:1)

我认为问题在于:

return (void *)block + 1;

被解释为:

((void *) block) + 1

因为演员的优先级高于加法。您可能会使用memblock覆盖*ptr = 4;结构。

[编辑]

我认为你应该做Eugene已在评论中提出的建议:

return (void *) (block + 1)