What is the difference between kmalloc, vmalloc and kzalloc?
Short answer: kmalloc(size, flags) returns physically contiguous memory from the slab allocator: fast, cache-friendly, usable for DMA (through the DMA API), and best for small to medium sizes (practically up to a few pages; large requests may fail when memory is fragmented). kzalloc is kmalloc plus zeroing, and kcalloc/kmalloc_array add overflow checks for arrays. vmalloc(size) returns memory that is virtually contiguous but physically scattered: good for large buffers, but slower (page-table setup, TLB pressure), it may sleep, and it is not directly usable for device DMA. kvmalloc tries kmalloc and falls back to vmalloc.
| kmalloc / kzalloc | vmalloc | alloc_pages | dma_alloc_coherent | |
|---|---|---|---|---|
| Physically contiguous | yes | no | yes (2^order pages) | yes (or IOMMU-contiguous) |
| Size | small–medium | large | whole pages | device buffers |
| Atomic context | yes with GFP_ATOMIC |
no | yes with GFP_ATOMIC |
depends; usually process context |
| Free with | kfree |
vfree |
__free_pages |
dma_free_coherent |
| Use for | structs, small buffers | large tables, module code | page-level buffers | DMA descriptors, shared buffers |
Other allocators to mention
kmem_cache_create/kmem_cache_alloc: dedicated slab caches for many objects of the same size (e.g. network buffers, inodes).devm_kzalloc: freed automatically when the device unbinds.- CMA (Contiguous Memory Allocator): large physically contiguous buffers for cameras/displays without IOMMU, reserved at boot, used through the DMA API.
- mempool: guaranteed allocations under memory pressure for I/O paths.
Common bugs: freeing with the wrong function (kfree on vmalloc memory), forgetting to check for NULL, kmalloc(n * size) overflow (use kmalloc_array), and DMA from stack or vmalloc buffers.