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.
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.
#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;
}demo: hits=0 misses=0 bytes=0Write 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.