You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This commit improves malloc() and free() in lib/c.c to
eliminate an unnecessary member from a structure and reduce
execution time.
First, the member 'ptr' is removed from 'chunk_t'. Originally,
it was used to return the starting address of a usable memory
region when calling malloc(). However, consider the following
code and illustration.
typedef struct chunk {
struct chunk *next;
struct chunk *prev;
int size;
} chunk_t;
chunk_t *chunk = ...
|<--- usable memory --->|
+------+------+------+-------- ... ----------+
| next | prev | size | : |
+------+------+------+-------- ... ----------+
^ ^
| |
chunk (chunk + 1)
the starting address returned by malloc().
After removing 'ptr' from 'chunk_t', the starting address of
the usable memory region can be obtained by adding 1 to a
pointer to 'chunk_t'. Thus, 'ptr' becomes unnecessary, so
this member is removed from the structure and malloc()
returns the starting address by the mentioned approach.
Second, for the free() function, after removing 'ptr' from
'chunk_t', the least significant bit of the member 'size' is
used to record a flag and prevent traversing the entire
allocation list.
The LSB of 'size' is used to check whether a chunk is freed
or not, and it is also used to speed up the free() function.
If a chunk is in the freelist, the LSB will be set to 1 to
indicate that the chunk is freed. Otherwise, the chunk is
still in the allocation list and usable when the LSB is 0,
and the memory region can be used by the caller who calls
malloc().
Next, when calling free(), the address of a chunk can be
obtained by moving a pointer which is the parameter of
free() backward by sizeof(chunk_t) bytes directly.
<--- usable memory --->
+------+------+------+------- ... -------------+
| next | prev | size | : |
+------+------+------+------- ... -------------+
^ ^
| |
chunk ptr
|<------------------>|
sizeof(chunk_t) bytes
Eventually, it is unnecessary to traverse the allocation list.
The address of a chunk can be obtained by moving the given
pointer backward, and the LSB of 'size' can be used to
validate the chunk, which can then be moved to the freelist.
Close#139
0 commit comments