aboutsummaryrefslogtreecommitdiffstats
path: root/src/alloc.c
blob: dd1c8aa420bfcf551752a6a87a23598e8d46b6ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * src/alloc.c
 *
 * Primary implementation of allocator logic for liballoc
 * CISC 301 -- Operating Systems, Project 3
 *
 * Copyright (C) 2025  Douglas B. Rumbaugh <dbrumbaugh@harrisburgu.edu>
 * 
 * Distributed under the Modified BSD License
 *
 */
#include "alloc.h"
#include "constants.h"
#include "free_list.h"
#include "alloc_header.h"

static void *heap_start = 0;
static void *heap_end = 0;
free_nd *free_list = NULL;

static void initialize() {
  heap_start = sbrk(0);

  if (heap_start == (void *)-1) {
    perror("liballoc initialization:");
    exit(EXIT_FAILURE);
  }

  size_t padding = (size_t)heap_start % ALIGNMENT;
  if (padding) {
    heap_start = sbrk(padding);
    if (heap_start == (void *)-1) {
      perror("liballoc initialization:");
      exit(EXIT_FAILURE);
    }
  }

  assert((size_t)heap_start % ALIGNMENT == 0);
  heap_end = heap_start;
}

void *allocate(size_t size) {
  if (!heap_start) {
    initialize();
  }

  /*
   * pad the requested size to ensure alignment using
   * the alignment one-liner we discussed in class
   */
  size = (size + ALIGNMENT - 1) & ~(ALIGNMENT - 1);

  /* first check for a suitable memory block on the free list */
  free_nd *nd = fl_find_first_fit(free_list, size);
  if (nd) {
    void *return_region = fl_split_node(&free_list, nd, size);
  }

  /*
   * if there aren't any blocks on the free list, we need to allocate
   * from scratch
   */
  void *new_region = sbrk(size + sizeof(header));

  /* out of memory */
  if (new_region == (void *)-1) {
    return NULL;
  }

  heap_end = new_region + size + sizeof(header);

  ((header *)new_region)->size = size;
  ((header *)new_region)->magic_number = MAGIC_NUMBER;

  return new_region + sizeof(header);
}

void release(void *ptr) {
  if (!ptr) {
    return;
  }

  fl_add_node(&free_list, ptr);
  fl_coalesce_nodes(free_list);
}

free_nd *free_list_head() {
  return free_list;
}