Reputation: 59
I know that kmalloc()
can replace malloc()
on kernel space. Many people think that the malloc()
can not run in kernel space; however, I found this definition atlinux-4.9.6/include/linux/decompress/mm.h
static void *malloc(int size)
{
void *p;
if (size < 0)
return NULL;
if (!malloc_ptr)
malloc_ptr = free_mem_ptr;
malloc_ptr = (malloc_ptr + 3) & ~3; /* Align */
p = (void *)malloc_ptr;
malloc_ptr += size;
if (free_mem_end_ptr && malloc_ptr >= free_mem_end_ptr)
return NULL;
malloc_count++;
return p;
}
Does it mean that we can use malloc()
on kernel level?
Upvotes: 2
Views: 1727
Reputation:
In a word: No.
The comment that precedes that code explains what it is for:
* Memory management for pre-boot and ramdisk uncompressors
This code is only used very early in system initialization, before kmalloc()
is available. (Possibly even before the code for it has been decompressed!) It is incredibly limited -- it cannot* free memory -- so it can only be used on a very small scale.
If you need to allocate memory in the kernel, you must use a function from the kmalloc()
family.
*: While there is an implementation of free()
paired with this malloc()
, it can only free memory under one very specific circumstance: when every single allocated block has been freed.
Upvotes: 3