alloc, free, create и destroy
Основные операции распределителя памяти.
«alloc, free, create и destroy» — бесплатный урок Zig Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Four Core Operations
An allocator gives you four key calls: alloc and free for many items, create and destroy for a single value.
alloc Returns a Slice
Use alloc to request a run of items. You pass the element type and a count, and you get back a slice of that many elements.
const buf = try a.alloc(u8, 64);alloc Can Fail
Because the heap can run out, alloc returns an error union. The try keyword handles the OutOfMemory case for you cleanly.
const list = try a.alloc(i32, 10);free Returns It
When you are done, call free with the exact slice you got. Forget this and the GeneralPurposeAllocator will report a leak.
a.free(buf);defer free Right Away
A common habit is to write defer a.free right after a successful alloc, so cleanup runs no matter how the scope exits.
const buf = try a.alloc(u8, 64);
defer a.free(buf);create for One Value
When you need exactly one heap value, use create. It takes a type and returns a single-item pointer to fresh memory.
const node = try a.create(Node);Write Through the Pointer
create gives you a pointer, so you set the value through it with .* before using the data it points to.
node.* = Node{ .value = 42 };destroy the Pointer
Release a created value with destroy, passing the same pointer create returned. This is the partner call to create.
a.destroy(node);Match the Pairs
The rule is strict: alloc pairs with free, and create pairs with destroy. Never cross them or free a slice you did not allocate.
Free with the Same Allocator
Always free memory using the same allocator that produced it. Mixing allocators leads to corruption the compiler cannot catch.
Errors Skip the defer Body
If alloc itself fails, no memory was made, so there is nothing to free. That is why defer free comes after a successful alloc. ✅
Quick Check
Match each allocation call with its correct release call.
Recap
You learned the pairs: alloc/free for slices and create/destroy for single values, always released with the same allocator. 🎯
Часто задаваемые вопросы
Урок «alloc, free, create и destroy» бесплатный?
Да — полный текст урока «alloc, free, create и destroy» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «alloc, free, create и destroy»?
Основные операции распределителя памяти. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «alloc, free, create и destroy»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Почему в Zig нет скрытых выделений памяти
- Интерфейс распределителя памяти
- alloc, free, create и destroy
- Динамические списки с ArrayList