La interfaz Allocator
Un contrato para todas las fuentes de memoria.
La interfaz Allocator es una lección gratuita de Zig Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Zig Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Zig Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
One Common Type
Every allocator in Zig is handed around as a single type, std.mem.Allocator. Your code talks to that one interface, never a concrete backend.
const Allocator = std.mem.Allocator;An Interface, Not a Class
std.mem.Allocator is a small interface: a pointer plus a table of functions. It describes what an allocator can do, not which one you use.
Many Backends, One Shape
A page allocator, an arena, or a test allocator all expose the same shape. Swapping one for another needs no change to calling code.
Get a Real Allocator
You obtain a concrete allocator, then take its .allocator() handle to pass around as the generic std.mem.Allocator type.
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const a = gpa.allocator();Pass It Down
Once you hold an allocator, you pass that one value into any function that needs memory. The whole program can share a single source.
try doWork(a);The Page Allocator
std.heap.page_allocator asks the OS directly for memory. It is simple but coarse, so it suits big or long-lived blocks, not tiny ones.
const a = std.heap.page_allocator;GeneralPurposeAllocator
The GeneralPurposeAllocator is the everyday choice in debug builds. It tracks every block and reports leaks and double-frees for you.
Why an Interface Helps
Coding against the interface means your function works with any allocator. The same code runs in tests, on bare metal, or in a server.
Functions Just Ask
A function does not care which allocator it got. It simply calls methods like alloc and free on the std.mem.Allocator it was given.
const buf = try a.alloc(u8, 16);No Global Allocator
Zig has no single global heap. You decide which allocator each part of your program uses, keeping memory sources visible and local.
Test with a Different One
In tests you pass std.testing.allocator instead. Same code, but now leaks fail the test, proving the interface pays off. ✅
Quick Check
Think about what type all Zig allocators share.
Recap
You learned that std.mem.Allocator is one interface over many backends, so code that asks for memory works with any allocator you supply. 🎯
Preguntas frecuentes
¿La lección «La interfaz Allocator» es gratis?
Sí — el texto completo de «La interfaz Allocator» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Zig Academy, actualiza a CoddyKit PRO. El curso de Zig Academy incluye 4 lecciones en total.
¿Qué aprenderé en «La interfaz Allocator»?
Un contrato para todas las fuentes de memoria. Practicas Zig Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Zig Academy?
No se requiere experiencia previa. Zig Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «La interfaz Allocator»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Zig Academy?
Sí. Cada lección de Zig Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Por qué Zig no tiene asignaciones ocultas
- La interfaz Allocator
- alloc, free, create, destroy
- Listas dinámicas con ArrayList