is memory allocated by kmalloc() ever automatically freed?
Asked Answered
U

2

11

I'm writing a device driver that, among other things, allocates a block of memory with kmalloc. This memory is freed when the user program closes the file. In one of my experiments, the user program crashed without closing the file.

Would anything have freed this memory?

In another experiment, I moved the kfree() from the close() function to the module_exit() function. When I ran the user program twice consecutively, I called kmalloc again with the same pointer as before, without freeing it first. Thus, I lost a pointer to that memory, and cannot free it.

Is this memory lost to the system until I reboot, or will it be freed when I unload the driver?

Unwieldy answered 25/7, 2012 at 19:42 Comment(1)
It will probably take a reboot. I'd imagine that the kernel won't go magically freeing up lost memory. The right way of going about doing this would be to hook program exit and free resources then. This is the same time a program's file descriptors are cleaned up.Lorient
S
13

Kernel memory is never freed automatically. This includes kmalloc.

All memory related to an open file descriptor should be released when the file is closed.
When a process exits, for any reason whatsoever (including kill -9), all open file descriptors are closed, and the driver's close function is called. So if you free there, nothing the process can do will make the memory stay after the process dies.

Stephainestephan answered 25/7, 2012 at 20:58 Comment(0)
J
7

Please don't relate your user-space experience with Kernel programming.

What do I mean by this?

Normal processes get a clean-up for them once they exit, that's not the case with kernel modules because they're not really processes.

Technically, when you load a module and then call kmalloc, what you did was that you asked the kernel to allocate some memory for you in the kernel space, it's technically a new memory for the whole kernel so even if you unload your module, that allocated kernel memory is there unless explicitly freed.

In simple terms answering your question: Every kmalloc needs a kfree, else the memory will remain there as long as the system is up.

Janina answered 25/7, 2012 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.