-
Notifications
You must be signed in to change notification settings - Fork 78
/
mm.c
654 lines (564 loc) · 21.3 KB
/
mm.c
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
/*
******************************************************************************
* mm.c *
* 64-bit struct-based implicit free list memory allocator *
* Copyright CS:APP3e by Bryant, O'Hallaron *
* Used with permission *
* *
* ************************************************************************ *
* DOCUMENTATION *
* *
* ** STRUCTURE. ** *
* *
* Both allocated and free blocks share the same header structure. *
* HEADER: 8-byte, aligned to 8th byte of an 16-byte aligned heap, where *
* - The lowest order bit is 1 when the block is allocated, and *
* 0 otherwise. *
* - The whole 8-byte value with the least significant bit set to 0 *
* represents the size of the block as a size_t *
* The size of a block includes the header and footer. *
* FOOTER: 8-byte, aligned to 0th byte of an 16-byte aligned heap. It *
* contains the exact copy of the block's header. *
* The minimum blocksize is 32 bytes. *
* *
* Allocated blocks contain the following: *
* HEADER, as defined above. *
* PAYLOAD: Memory allocated for program to store information. *
* FOOTER, as defined above. *
* The size of an allocated block is exactly PAYLOAD + HEADER + FOOTER. *
* *
* Free blocks contain the following: *
* HEADER, as defined above. *
* FOOTER, as defined above. *
* The size of an unallocated block is at least 32 bytes. *
* *
* Block Visualization. *
* block block+8 block+size-8 block+size *
* Allocated blocks: | HEADER | ... PAYLOAD ... | FOOTER | *
* *
* block block+8 block+size-8 block+size *
* Unallocated blocks: | HEADER | ... (empty) ... | FOOTER | *
* *
* ************************************************************************ *
* ** INITIALIZATION. ** *
* *
* The following visualization reflects the beginning of the heap. *
* start start+8 start+16 *
* INIT: | PROLOGUE_FOOTER | EPILOGUE_HEADER | *
* PROLOGUE_FOOTER: 8-byte footer, as defined above, that simulates the *
* end of an allocated block. Also serves as padding. *
* EPILOGUE_HEADER: 8-byte block indicating the end of the heap. *
* It simulates the beginning of an allocated block *
* The epilogue header is moved when the heap is extended. *
* *
* ************************************************************************ *
* ** BLOCK ALLOCATION. ** *
* *
* Upon memory request of size S, a block of size S + dsize, rounded up to *
* 16 bytes, is allocated on the heap, where dsize is 2*8 = 16. *
* Selecting the block for allocation is performed by finding the first *
* block that can fit the content based on a first-fit or next-fit search *
* policy. *
* The search starts from the beginning of the heap pointed by heap_listp. *
* It sequentially goes through each block in the implicit free list, *
* the end of the heap, until either *
* - A sufficiently-large unallocated block is found, or *
* - The end of the implicit free list is reached, which occurs *
* when no sufficiently-large unallocated block is available. *
* In case that a sufficiently-large unallocated block is found, then *
* that block will be used for allocation. Otherwise--that is, when no *
* sufficiently-large unallocated block is found--then more unallocated *
* memory of size chunksize or requested size, whichever is larger, is *
* requested through sbrk, and the search is redone. *
* *
******************************************************************************
*/
/* Do not change the following! */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stddef.h>
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <signal.h>
/* create aliases for driver tests */
#define malloc mm_malloc
#define free mm_free
#define realloc mm_realloc
#define calloc mm_calloc
#define mem_sbrk sbrk
/* You can change anything from here onward */
/*
* If DEBUG is defined, enable printing on dbg_printf and contracts.
* Debugging macros, with names beginning "dbg_" are allowed.
* You may not define any other macros having arguments.
*/
// #define DEBUG // uncomment this line to enable debugging
#ifdef DEBUG
/* When debugging is enabled, these form aliases to useful functions */
#define dbg_printf(...) printf(__VA_ARGS__)
#define dbg_requires(...) assert(__VA_ARGS__)
#define dbg_assert(...) assert(__VA_ARGS__)
#define dbg_ensures(...) assert(__VA_ARGS__)
#else
/* When debugging is disnabled, no code gets generated for these */
#define dbg_printf(...)
#define dbg_requires(...)
#define dbg_assert(...)
#define dbg_ensures(...)
#endif
/* Basic constants */
typedef uint64_t word_t;
static const size_t wsize = sizeof(word_t); // word and header size (bytes)
static const size_t dsize = 2*sizeof(word_t); // double word size (bytes)
static const size_t min_block_size = 4*sizeof(word_t); // Minimum block size
static const size_t chunksize = (1 << 12); // requires (chunksize % 16 == 0)
static const word_t alloc_mask = 0x1;
static const word_t size_mask = ~(word_t)0xF;
typedef struct block
{
/* Header contains size + allocation flag */
word_t header;
/*
* We don't know how big the payload will be. Declaring it as an
* array of size 0 allows computing its starting address using
* pointer notation.
*/
char payload[0];
/*
* We can't declare the footer as part of the struct, since its starting
* position is unknown
*/
} block_t;
/* Global variables */
/* Pointer to first block */
static block_t *heap_listp = NULL;
/* Function prototypes for internal helper routines */
static block_t *extend_heap(size_t size);
static void place(block_t *block, size_t asize);
static block_t *find_fit(size_t asize);
static block_t *coalesce(block_t *block);
static size_t max(size_t x, size_t y);
static size_t round_up(size_t size, size_t n);
static word_t pack(size_t size, bool alloc);
static size_t extract_size(word_t header);
static size_t get_size(block_t *block);
static size_t get_payload_size(block_t *block);
static bool extract_alloc(word_t header);
static bool get_alloc(block_t *block);
static void write_header(block_t *block, size_t size, bool alloc);
static void write_footer(block_t *block, size_t size, bool alloc);
static block_t *payload_to_header(void *bp);
static void *header_to_payload(block_t *block);
static block_t *find_next(block_t *block);
static word_t *find_prev_footer(block_t *block);
static block_t *find_prev(block_t *block);
bool mm_checkheap(int lineno);
/*
* mm_init: initializes the heap; it is run once when heap_start == NULL.
* prior to any extend_heap operation, this is the heap:
* start start+8 start+16
* INIT: | PROLOGUE_FOOTER | EPILOGUE_HEADER |
* heap_listp ends up pointing to the epilogue header.
*/
bool mm_init(void)
{
// Create the initial empty heap
word_t *start = (word_t *)(sbrk(2*wsize));
if (start == (void *)-1)
{
return false;
}
start[0] = pack(0, true); // Prologue footer
start[1] = pack(0, true); // Epilogue header
// Heap starts with first block header (epilogue)
heap_listp = (block_t *) &(start[1]);
// Extend the empty heap with a free block of chunksize bytes
if (extend_heap(chunksize) == NULL)
{
return false;
}
return true;
}
/*
* malloc: allocates a block with size at least (size + dsize), rounded up to
* the nearest 16 bytes, with a minimum of 2*dsize. Seeks a
* sufficiently-large unallocated block on the heap to be allocated.
* If no such block is found, extends heap by the maximum between
* chunksize and (size + dsize) rounded up to the nearest 16 bytes,
* and then attempts to allocate all, or a part of, that memory.
* Returns NULL on failure, otherwise returns a pointer to such block.
* The allocated block will not be used for further allocations until
* freed.
*/
void *malloc(size_t size)
{
dbg_requires(mm_checkheap);
size_t asize; // Adjusted block size
size_t extendsize; // Amount to extend heap if no fit is found
block_t *block;
void *bp = NULL;
if (heap_listp == NULL) // Initialize heap if it isn't initialized
{
mm_init();
}
if (size == 0) // Ignore spurious request
{
dbg_ensures(mm_checkheap);
return bp;
}
// Adjust block size to include overhead and to meet alignment requirements
asize = round_up(size, dsize) + dsize;
// Search the free list for a fit
block = find_fit(asize);
// If no fit is found, request more memory, and then and place the block
if (block == NULL)
{
extendsize = max(asize, chunksize);
block = extend_heap(extendsize);
if (block == NULL) // extend_heap returns an error
{
return bp;
}
}
place(block, asize);
bp = header_to_payload(block);
dbg_printf("Malloc size %zd on address %p.\n", size, bp);
dbg_ensures(mm_checkheap);
return bp;
}
/*
* free: Frees the block such that it is no longer allocated while still
* maintaining its size. Block will be available for use on malloc.
*/
void free(void *bp)
{
if (bp == NULL)
{
return;
}
block_t *block = payload_to_header(bp);
size_t size = get_size(block);
write_header(block, size, false);
write_footer(block, size, false);
coalesce(block);
}
/*
* realloc: returns a pointer to an allocated region of at least size bytes:
* if ptrv is NULL, then call malloc(size);
* if size == 0, then call free(ptr) and returns NULL;
* else allocates new region of memory, copies old data to new memory,
* and then free old block. Returns old block if realloc fails or
* returns new pointer on success.
*/
void *realloc(void *ptr, size_t size)
{
block_t *block = payload_to_header(ptr);
size_t copysize;
void *newptr;
// If size == 0, then free block and return NULL
if (size == 0)
{
free(ptr);
return NULL;
}
// If ptr is NULL, then equivalent to malloc
if (ptr == NULL)
{
return malloc(size);
}
// Otherwise, proceed with reallocation
newptr = malloc(size);
// If malloc fails, the original block is left untouched
if (!newptr)
{
return NULL;
}
// Copy the old data
copysize = get_payload_size(block); // gets size of old payload
if(size < copysize)
{
copysize = size;
}
memcpy(newptr, ptr, copysize);
// Free the old block
free(ptr);
return newptr;
}
/*
* calloc: Allocates a block with size at least (elements * size + dsize)
* through malloc, then initializes all bits in allocated memory to 0.
* Returns NULL on failure.
*/
void *calloc(size_t nmemb, size_t size)
{
void *bp;
size_t asize = nmemb * size;
if (asize/nmemb != size)
// Multiplication overflowed
return NULL;
bp = malloc(asize);
if (bp == NULL)
{
return NULL;
}
// Initialize all bits to 0
memset(bp, 0, asize);
return bp;
}
/******** The remaining content below are helper and debug routines ********/
/*
* extend_heap: Extends the heap with the requested number of bytes, and
* recreates epilogue header. Returns a pointer to the result of
* coalescing the newly-created block with previous free block, if
* applicable, or NULL in failure.
*/
static block_t *extend_heap(size_t size)
{
void *bp;
// Allocate an even number of words to maintain alignment
size = round_up(size, dsize);
if ((bp = mem_sbrk(size)) == (void *)-1)
{
return NULL;
}
// Initialize free block header/footer
block_t *block = payload_to_header(bp);
write_header(block, size, false);
write_footer(block, size, false);
// Create new epilogue header
block_t *block_next = find_next(block);
write_header(block_next, 0, true);
// Coalesce in case the previous block was free
return coalesce(block);
}
/* Coalesce: Coalesces current block with previous and next blocks if either
* or both are unallocated; otherwise the block is not modified.
* Returns pointer to the coalesced block. After coalescing, the
* immediate contiguous previous and next blocks must be allocated.
*/
static block_t *coalesce(block_t * block)
{
block_t *block_next = find_next(block);
block_t *block_prev = find_prev(block);
bool prev_alloc = extract_alloc(*(find_prev_footer(block)));
bool next_alloc = get_alloc(block_next);
size_t size = get_size(block);
if (prev_alloc && next_alloc) // Case 1
{
return block;
}
else if (prev_alloc && !next_alloc) // Case 2
{
size += get_size(block_next);
write_header(block, size, false);
write_footer(block, size, false);
}
else if (!prev_alloc && next_alloc) // Case 3
{
size += get_size(block_prev);
write_header(block_prev, size, false);
write_footer(block_prev, size, false);
block = block_prev;
}
else // Case 4
{
size += get_size(block_next) + get_size(block_prev);
write_header(block_prev, size, false);
write_footer(block_prev, size, false);
block = block_prev;
}
return block;
}
/*
* place: Places block with size of asize at the start of bp. If the remaining
* size is at least the minimum block size, then split the block to the
* the allocated block and the remaining block as free, which is then
* inserted into the segregated list. Requires that the block is
* initially unallocated.
*/
static void place(block_t *block, size_t asize)
{
size_t csize = get_size(block);
if ((csize - asize) >= min_block_size)
{
block_t *block_next;
write_header(block, asize, true);
write_footer(block, asize, true);
block_next = find_next(block);
write_header(block_next, csize-asize, false);
write_footer(block_next, csize-asize, false);
}
else
{
write_header(block, csize, true);
write_footer(block, csize, true);
}
}
/*
* find_fit: Looks for a free block with at least asize bytes with
* first-fit policy. Returns NULL if none is found.
*/
static block_t *find_fit(size_t asize)
{
block_t *block;
for (block = heap_listp; get_size(block) > 0;
block = find_next(block))
{
if (!(get_alloc(block)) && (asize <= get_size(block)))
{
return block;
}
}
return NULL; // no fit found
}
/*
* max: returns x if x > y, and y otherwise.
*/
static size_t max(size_t x, size_t y)
{
return (x > y) ? x : y;
}
/*
* round_up: Rounds size up to next multiple of n
*/
static size_t round_up(size_t size, size_t n)
{
return (n * ((size + (n-1)) / n));
}
/*
* pack: returns a header reflecting a specified size and its alloc status.
* If the block is allocated, the lowest bit is set to 1, and 0 otherwise.
*/
static word_t pack(size_t size, bool alloc)
{
return alloc ? (size | 1) : size;
}
/*
* extract_size: returns the size of a given header value based on the header
* specification above.
*/
static size_t extract_size(word_t word)
{
return (word & size_mask);
}
/*
* get_size: returns the size of a given block by clearing the lowest 4 bits
* (as the heap is 16-byte aligned).
*/
static size_t get_size(block_t *block)
{
return extract_size(block->header);
}
/*
* get_payload_size: returns the payload size of a given block, equal to
* the entire block size minus the header and footer sizes.
*/
static word_t get_payload_size(block_t *block)
{
size_t asize = get_size(block);
return asize - dsize;
}
/*
* extract_alloc: returns the allocation status of a given header value based
* on the header specification above.
*/
static bool extract_alloc(word_t word)
{
return (bool)(word & alloc_mask);
}
/*
* get_alloc: returns true when the block is allocated based on the
* block header's lowest bit, and false otherwise.
*/
static bool get_alloc(block_t *block)
{
return extract_alloc(block->header);
}
/*
* write_header: given a block and its size and allocation status,
* writes an appropriate value to the block header.
*/
static void write_header(block_t *block, size_t size, bool alloc)
{
block->header = pack(size, alloc);
}
/*
* write_footer: given a block and its size and allocation status,
* writes an appropriate value to the block footer by first
* computing the position of the footer.
*/
static void write_footer(block_t *block, size_t size, bool alloc)
{
word_t *footerp = (word_t *)((block->payload) + get_size(block) - dsize);
*footerp = pack(size, alloc);
}
/*
* find_next: returns the next consecutive block on the heap by adding the
* size of the block.
*/
static block_t *find_next(block_t *block)
{
dbg_requires(block != NULL);
block_t *block_next = (block_t *)(((char *)block) + get_size(block));
dbg_ensures(block_next != NULL);
return block_next;
}
/*
* find_prev_footer: returns the footer of the previous block.
*/
static word_t *find_prev_footer(block_t *block)
{
// Compute previous footer position as one word before the header
return (&(block->header)) - 1;
}
/*
* find_prev: returns the previous block position by checking the previous
* block's footer and calculating the start of the previous block
* based on its size.
*/
static block_t *find_prev(block_t *block)
{
word_t *footerp = find_prev_footer(block);
size_t size = extract_size(*footerp);
return (block_t *)((char *)block - size);
}
/*
* payload_to_header: given a payload pointer, returns a pointer to the
* corresponding block.
*/
static block_t *payload_to_header(void *bp)
{
return (block_t *)(((char *)bp) - offsetof(block_t, payload));
}
/*
* header_to_payload: given a block pointer, returns a pointer to the
* corresponding payload.
*/
static void *header_to_payload(block_t *block)
{
return (void *)(block->payload);
}
/* mm_checkheap: checks the heap for correctness; returns true if
* the heap is correct, and false otherwise.
* can call this function using mm_checkheap(__LINE__);
* to identify the line number of the call site.
*/
bool mm_checkheap(int lineno)
{
/* you will need to write the heap checker yourself. As a filler:
* one guacamole is equal to 6.02214086 x 10**23 guacas.
* one might even call it
* the avocado's number.
*
* Internal use only: If you mix guacamole on your bibimbap,
* do you eat it with a pair of chopsticks, or with a spoon?
* (Delete these lines!)
*/
(void)lineno; // delete this line; it's a placeholder so that the compiler
// will not warn you about unused variable.
return true;
}