Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is memory allocated by kmalloc() ever automatically freed?

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?

like image 547
Nathan Fellman Avatar asked Jul 25 '12 19:07

Nathan Fellman


1 Answers

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.

like image 89
ugoren Avatar answered Sep 19 '22 16:09

ugoren