Skip to content

Update global_allocator to use the attribute template #1919

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions src/runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,43 @@ This section documents features that define some aspects of the Rust runtime.
r[runtime.global_allocator]
## The `global_allocator` attribute

The *`global_allocator` attribute* is used on a [static item] implementing the
[`GlobalAlloc`] trait to set the global allocator.
r[runtime.global_allocator.intro]
The *`global_allocator` [attribute][attributes]* selects a [memory allocator][std::alloc].

> [!EXAMPLE]
> ```rust
> use core::alloc::{GlobalAlloc, Layout};
> use std::alloc::System;
>
> struct MyAllocator;
>
> unsafe impl GlobalAlloc for MyAllocator {
> unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
> unsafe { System.alloc(layout) }
> }
> unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
> unsafe { System.dealloc(ptr, layout) }
> }
> }
>
> #[global_allocator]
> static GLOBAL: MyAllocator = MyAllocator;
> ```

r[runtime.global_allocator.syntax]
The `global_allocator` attribute uses the [MetaWord] syntax.

r[runtime.global_allocator.allowed-positions]
The `global_allocator` attribute may only be applied to a [static item] whose type implements the [`GlobalAlloc`] trait.

r[runtime.global_allocator.duplicates]
The `global_allocator` attribute may only be used once on an item.

r[runtime.global_allocator.single]
The `global_allocator` attribute may only be used once in the crate graph.

r[runtime.global_allocator.stdlib]
The `global_allocator` attribute is exported from the [standard library prelude][core::prelude::v1].

r[runtime.windows_subsystem]
## The `windows_subsystem` attribute
Expand Down