@@ -24,7 +24,7 @@ Arena* new_arena() {
24
24
* arena = (Arena ) {
25
25
.nblocks = 0 ,
26
26
.maxblocks = 256 ,
27
- .blocks = malloc (256 * sizeof (size_t )),
27
+ .blocks = malloc (256 * sizeof (void * )),
28
28
.available = 0 ,
29
29
};
30
30
for (int i = 0 ; i < arena -> maxblocks ; i ++ )
@@ -40,20 +40,39 @@ void destroy_arena(Arena* arena) {
40
40
free (arena );
41
41
}
42
42
43
+ static void * new_block (Arena * arena , size_t size ) {
44
+ assert (arena -> nblocks <= arena -> maxblocks );
45
+ // we need more storage for the block pointers themselves !
46
+ if (arena -> nblocks == arena -> maxblocks ) {
47
+ arena -> maxblocks *= 2 ;
48
+ arena -> blocks = realloc (arena -> blocks , arena -> maxblocks * sizeof (void * ));
49
+ }
50
+
51
+ void * allocated = malloc (size );
52
+ assert (allocated );
53
+ arena -> blocks [arena -> nblocks ++ ] = allocated ;
54
+ return allocated ;
55
+ }
56
+
43
57
void * arena_alloc (Arena * arena , size_t size ) {
44
58
size = round_up (size , (size_t ) sizeof (max_align_t ));
45
59
if (size == 0 )
46
60
return NULL ;
47
- // arena is full
48
- if (size > arena -> available ) {
49
- assert (arena -> nblocks <= arena -> maxblocks );
50
- // we need more storage for the block pointers themselves !
51
- if (arena -> nblocks == arena -> maxblocks ) {
52
- arena -> maxblocks *= 2 ;
53
- arena -> blocks = realloc (arena -> blocks , arena -> maxblocks );
61
+ if (size > alloc_size ) {
62
+ void * allocated = new_block (arena , size );
63
+ memset (allocated , 0 , size );
64
+ // swap the last two blocks
65
+ if (arena -> nblocks >= 2 ) {
66
+ void * swap = arena -> blocks [arena -> nblocks - 1 ];
67
+ arena -> blocks [arena -> nblocks - 1 ] = arena -> blocks [arena -> nblocks - 2 ];
68
+ arena -> blocks [arena -> nblocks - 2 ] = swap ;
54
69
}
70
+ return allocated ;
71
+ }
55
72
56
- arena -> blocks [arena -> nblocks ++ ] = malloc (alloc_size );
73
+ // arena is full
74
+ if (size > arena -> available ) {
75
+ new_block (arena , alloc_size );
57
76
arena -> available = alloc_size ;
58
77
}
59
78
0 commit comments