memmain.cpp

来自「经典c++程序的实现」· C++ 代码 · 共 42 行

CPP
42
字号
#include <iostream.h>
#include <stdlib.h>

#define MINEXTRA 6
#define RESERVED 1
#define FREE 0

int* pick_free_block(int x) { return NULL; }
int MemoryPool[1];

#define STARTTAG 0
#define SIZE 1
#define PREV 2
#define NEXT 3
#define ENDSIZE 4
#define ENDTAG 5

int* allocate(int m) // Return a block with at least m free spaces
{ // The size field will store the actual number of free
  // spaces, not including maintenance fields
  if (m < 3) m = 3; // Must be big enough to be a free block later
  int* temp = pick_free_block(m);   // Must be at least m+3 units
  if (temp[SIZE] >= m+MINEXTRA) {   // Split block, save excess
    int start = temp[SIZE] - m + 3; // First unit of reserved block
    temp[start] = temp[temp[SIZE] + ENDTAG] = RESERVED;
    temp[start+SIZE] = m;
    temp[SIZE] -= m+3;  // This much was reserved
    temp[temp[SIZE] + ENDSIZE] = temp[SIZE];
    temp[temp[SIZE] + ENDTAG] = FREE;
    return &temp[start];
  }
  else { // give over the whole block, remove from free list
    temp[STARTTAG] = temp[temp[SIZE] + ENDTAG] = RESERVED;
    temp[SIZE] += 3; // for the extra maintenance fields
    // Freelist pointers point directly to pointer positions
    // of neighboring blocks in array MemoryPool.
    MemoryPool[temp[PREV]] = temp[NEXT];
    MemoryPool[temp[NEXT]] = temp[PREV];
    return temp;
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?