RE: What's the standard for dynamically allocating memory?

Nick Huang <[email protected]> Wed, 3 Dec 2025 19:21:30 +0800
Newsgroups org.kernel.vger.linux-newbie
Message-ID <[email protected]>
Hi Dilan,

For memory allocation inside the Linux kernel, there is no single
“universal” function — the choice depends on *context*, *lifetime*, and
*constraints* of the allocation. The commonly used interfaces are:

1. **kmalloc() / kfree()**
   - Allocates physically contiguous memory.
   - Good for small objects and structures.
   - GFP flags control allocation behavior (e.g., GFP_KERNEL, GFP_ATOMIC).

2. **kzalloc()**
   - Same as kmalloc() but zeroes memory.

3. **vmalloc() / vfree()**
   - Allocates virtually contiguous memory (not physically contiguous).
   - Suitable for larger buffers.

4. **devm_kmalloc()**
   - Managed allocation tied to device lifetime.
   - Automatically freed when the device is removed.

5. **kmem_cache (slab allocator)**
   - For frequently allocated objects of the same size.

The kernel documentation describes the rules and trade-offs here:
  Documentation/core-api/memory-allocation.rst

In general:
- Prefer kmalloc/kzalloc when possible.
- Use vmalloc only if large sizes are required.
- Use GFP_ATOMIC only in non-sleepable contexts.

Hope this helps!

Nick