Comparing kmalloc, vmalloc, and malloc Memory Allocation Functions
All three memory allocation functions kmalloc, vmalloc, and malloc allocate memory in units of bytes.
kmalloc
void * kmalloc(size_t requested_size, gfp_t gfp_flags)
This function returns a pointer to a memory block of at least the requested size. The allocated memory is physically contiguous and retains the original data from the memory region (it does not zero the block before returning).
Common allocation flag values:
GFP_USER: Used for user space memory allocations, may allow the caller to sleepGFP_KERNEL: Used for general kernel space memory allocations, may allow the caller to sleepGFP_ATOMIC: Used for atomic memory allocations in contexts where blocking is not allowed, will never sleep; common use cases include interrupt handlers, softirqs, and tasklets
kmalloc ultimately calls __get_free_pages to perform the actual underlying page allocation, which is why all its flags use the GFP_ prefix. The maximum allocation size for kmalloc is 32 pages, which equals 128KB on systems with 4KB pages, and 16 bytes of thiss space is used to store page descriptor metadata. All allocations from kmalloc are permanently resident in physical memory and cannot be swapped out to disk. The minimum allocation granularity is 32 or 64 bytes, depending on the system architecture.
kzalloc
kzalloc() is a convenience wrapper that allocates memory and automatically initializes all bytes of the block to 0. It is functionally equivalent to calling kmalloc() then using memset() to zero the allocated region.
static inline void *kzalloc(size_t requested_size, gfp_t gfp_flags)
{
return kmalloc(requested_size, gfp_flags | __GFP_ZERO);
}
The __GFP_ZERO flag passed via bitwise OR to kmalloc handles the zero initialization automatically.
vmalloc
void * vmalloc(unsigned long requested_size)
This function returns a pointer to a memory block of at least the requested size, and only guarantees the memory is contiguous in the virtual address space. Unlike kmalloc, vmalloc does not accept custom allocation flags, and is always allowed to sleep.
| Allocation Function | Address Space | Contiguity | Maximum Size | Release Function | Key Advantage |
|---|---|---|---|---|---|
| kmalloc | Kernel space | Physically contiguous | 128KB - 16 bytes (4KB page system) | kfree | Higher allocation performance |
| vmalloc | Kernel space | Only virtual address contiguous | Supports much larger allocations | vfree | Easier to allocate large memory blocks |
| malloc | User space | Only virtual address contiguous | Supports very large allocations | free |