本文主要是介绍linux内核函数 devm_kzalloc()和devm_kfree(),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
函数devm_kzalloc()和kzalloc()一样都是内核内存分配函数,但是devm_kzalloc()是跟设备(装置)有关的,当设备(装置)被拆卸或者驱动(驱动程序)卸载(空载)时,内存会被自动释放。另外,当内存不在使用时,可以使用函数devm_kfree()释放。
而kzalloc()则需要手动释放(使用kfree()),但如果工程师检查不仔细,则有可能造成内存泄漏。
注:也就是在驱动的探针函数中调用devm_kzalloc(),在除去函数中调用devm_kfree()函数
static inline void * devm_kzalloc(struct device * dev,size_t size,gfp_t gfp)
{return devm_kmalloc(dev,size,gfp | __GFP_ZERO);
}
/*** devm_kmalloc - Resource-managed kmalloc * @dev: Device to allocate memory for //struct device* @size: Allocation size //memory size* @gfp: Allocation gfp flags //gfp flag** Managed kmalloc. Memory allocated with this function is* automatically freed on driver detach. Like all other devres * resources, guaranteed alignment is unsigned long long. //memory 对齐** RETURNS:* Pointer to allocated memory on success, NULL on failure. //成功返回首地质,失败返回NULL*/
void * devm_kmalloc(struct device *dev, size_t size, gfp_t gfp)
{struct devres *dr;/* use raw alloc_dr for kmalloc caller tracing */dr = alloc_dr(devm_kmalloc_release, size, gfp, dev_to_node(dev));if (unlikely(!dr))return NULL;/* * This is named devm_kzalloc_release for historical reasons* The initial implementation did not support kmalloc, only kzalloc*/set_node_dbginfo(&dr->node, "devm_kzalloc_release", size);devres_add(dev, dr->data);return dr->data;
}
EXPORT_SYMBOL_GPL(devm_kmalloc);
/** * devm_kfree - Resource-managed kfree* @dev: Device this memory belongs to* @p: Memory to free* * Free memory allocated with devm_kmalloc().*/
void devm_kfree(struct device * dev,void * p)
{int rc;
rc = devres_destroy(dev,devm_kmalloc_release,devm_kmalloc_match,p);WARN_ON(RC);
}
EXPORT_SYMBOL_GPL(devm_kfree);
详情参考:HTTPS://blog.csdn.net/jgw2008/article/details/52691568
注:内核版本:4.9
这篇关于linux内核函数 devm_kzalloc()和devm_kfree()的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!