# problem with malloc/free in kernel module



## yizhinantian (May 5, 2010)

Hi,
    i got some problem with malloc/free in kernel.

OS: FREEBSD_7.3_RELEASE AMD64
CPU: INTER 4 core.  
RAM: 2GB

i allocated about 512M memory, seems like this:

```
func a()
{
 for(i=0; i<MAX_SESSION_NODE; i++)
 {
   tmp=malloc(128, M_DEVBUF, M_NOWAIT|M_ZERO);
    if( tmp != NULL)
   .....
 }
}
```

a was called by a pci driver's device_attach function.

In driver's device_detach function, i try to release all the 512 memory.

```
for(...)
{
 free(x, M_DEVBUF);
}
```

.
when i 
1.first load the driver. 
"top" cmd shows about 512M mem has been wired. about 1.5G free.
"vmstat -m" shows devbuf hold more than 512M mem.

2.unload the driver.
"top" cmd still shows about 512M mem has been wired. about 1.5G free
"vmstat -m" show devbuf freed 512M mem (only hold very little mem).

3.reload driver
"top" cmd shows about 512M mem has been wired. about 1.5G free.
"vmstat -m" shows devbuf hold more than512M mem.

so my question is:
1. if memory is not freed successfully, why step 3 didn't allocate another 512M mem.
2. if memory is freed successfully, why "top" shows the 512M mem is wired.


btw:
i check about 10 address returnd by malloc with the parameter of free, both right.


any suggestion or hint will be appreciated.


----------



## expl (May 5, 2010)

As far as I understand kernel never marks memory as free, as free memory is 'never used before' memory, it just marks the freed area as unused.


----------

