Skip to content

Commit c8e0f95

Browse files
committed
update chapter4 part2: heap allocator
move global allocator to memory mod.
1 parent d9774f8 commit c8e0f95

File tree

1 file changed

+24
-21
lines changed

1 file changed

+24
-21
lines changed

chapter4/part2.md

+24-21
Original file line numberDiff line numberDiff line change
@@ -60,29 +60,34 @@ unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);
6060

6161
[dependencies]
6262
buddy_system_allocator = "0.3"
63+
```
6364

65+
```rust
6466
// src/lib.rs
65-
// Rust 要求 global allocator 必须在 lib.rs 中定义,因此不能放在 memory 子模块里面
66-
#![feature(alloc_error_handler)]
67-
68-
use buddy_system_allocator::LockedHeap;
6967

70-
#[global_allocator]
71-
static DYNAMIC_ALLOCATOR: LockedHeap = LockedHeap::empty();
68+
#![feature(alloc_error_handler)]
7269

73-
#[alloc_error_handler]
74-
fn alloc_error_handler(_: core::alloc::Layout) -> ! {
75-
panic!("alloc_error_handler do nothing but panic!");
76-
}
70+
extern crate alloc;
71+
```
7772

73+
```rust
7874
// src/consts.rs
75+
7976
// 内核堆大小为8MiB
8077
pub const KERNEL_HEAP_SIZE: usize = 0x800000;
78+
```
8179

80+
```rust
8281
// src/memory/mod.rs
8382

84-
use crate::DYNAMIC_ALLOCATOR;
8583
use crate::consts::*;
84+
use buddy_system_allocator::LockedHeap;
85+
86+
pub fn init(l: usize, r: usize) {
87+
FRAME_ALLOCATOR.lock().init(l, r);
88+
init_heap();
89+
println!("++++ setup memory! ++++");
90+
}
8691

8792
fn init_heap() {
8893
// 同样是在内核中开一块静态内存供 buddy system allocator 使用
@@ -95,10 +100,12 @@ fn init_heap() {
95100
}
96101
}
97102

98-
pub fn init(l: usize, r: usize) {
99-
FRAME_ALLOCATOR.lock().init(l, r);
100-
init_heap();
101-
println!("++++ setup memory! ++++");
103+
#[global_allocator]
104+
static DYNAMIC_ALLOCATOR: LockedHeap = LockedHeap::empty();
105+
106+
#[alloc_error_handler]
107+
fn alloc_error_handler(_: core::alloc::Layout) -> ! {
108+
panic!("alloc_error_handler do nothing but panic!");
102109
}
103110
```
104111

@@ -107,10 +114,6 @@ pub fn init(l: usize, r: usize) {
107114
现在我们来测试一下动态内存分配是否有效,分别动态分配一个整数和一个数组:
108115

109116
```rust
110-
// src/lib.rs
111-
112-
extern crate alloc;
113-
114117
// src/init.rs
115118

116119
fn dynamic_allocating_test() {
@@ -152,10 +155,10 @@ fn dynamic_allocating_test() {
152155
>
153156
> ```rust
154157
> heap_value assertion successfully!
155-
> heap_value is at 0xffffffffc0a15100
158+
> heap_value is at 0x80a10000
156159
> heap_value is in section .bss!
157160
> vec assertion successfully!
158-
> vec is at 0xffffffffc0a14000
161+
> vec is at 0x80211000
159162
> vec is in section .bss!
160163
> ```
161164

0 commit comments

Comments
 (0)