Skip to content
systemcoding.dev
Kernels

Allocate zeroed kernel memory with kzalloc

Use kzalloc(sizeof(*p), GFP_KERNEL) instead of kmalloc plus memset so new kernel structures never leak stale heap bytes to user space on Linux 6.x.

1 min read
Summarize in AI

kmalloc() returns whatever bytes the slab last held. A structure you copy to user space with copy_to_user() and only half fill leaks that old kernel memory, which is a real class of CVE. kzalloc() is kmalloc() with __GFP_ZERO, so every byte starts at zero and padding between fields is covered too.

c
#include <linux/slab.h>

struct demo_stats {
	u32 hits;
	u32 misses;
	u64 bytes;
};

static struct demo_stats *demo_alloc(void)
{
	struct demo_stats *s;

	s = kzalloc(sizeof(*s), GFP_KERNEL);
	if (!s)
		return NULL;
	pr_info("demo: hits=%u misses=%u bytes=%llu\n",
		s->hits, s->misses, s->bytes);
	return s;
}
Text
demo: hits=0 misses=0 bytes=0

Write sizeof(*s), not sizeof(struct demo_stats). If the variable's type changes, the size follows automatically, and the kernel coding style asks for it. GFP_KERNEL may sleep, so it is for process context only; in an interrupt handler or under a spinlock use GFP_ATOMIC, which can fail far more often.

Zeroing is not free: it writes every byte, so for a large buffer you are about to overwrite entirely, plain kmalloc() is the better choice. For big sizes, kzalloc() also stays physically contiguous and can fail when memory is fragmented; kvzalloc() falls back to vmalloc. See the memory allocation guide.

Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.