您好,登錄后才能下訂單哦!
這篇文章主要講解了“Linux內(nèi)核內(nèi)存分配函數(shù)kzalloc和kcalloc怎么使用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Linux內(nèi)核內(nèi)存分配函數(shù)kzalloc和kcalloc怎么使用”吧!
文件:include/linux/slab.h
,定義如下:
/** * kzalloc - allocate memory. The memory is set to zero. * @size: how many bytes of memory are required. * @flags: the type of memory to allocate (see kmalloc). */static inline void *kzalloc(size_t size, gfp_t flags){ return kmalloc(size, flags | __GFP_ZERO);}
kzalloc()
函數(shù)功能同kmalloc()
。區(qū)別:內(nèi)存分配成功后清零。
每次使用kzalloc()
后,都要有對應(yīng)的內(nèi)存釋放函數(shù)kfree()
。
舉例:
static int rockchip_drm_open(struct drm_device *dev, struct drm_file *file){ ... file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL); ... kfree(file_priv); file_priv = NULL; ...}
文件:include/linux/slab.h
,定義如下:
/** * kmalloc_array - allocate memory for an array. * @n: number of elements. * @size: element size. * @flags: the type of memory to allocate (see kmalloc). */static inline void *kmalloc_array(size_t n, size_t size, gfp_t flags){ if (size != 0 && n > SIZE_MAX / size) return NULL; return __kmalloc(n * size, flags);}/** * kcalloc - allocate memory for an array. The memory is set to zero. * @n: number of elements. * @size: element size. * @flags: the type of memory to allocate (see kmalloc). */static inline void *kcalloc(size_t n, size_t size, gfp_t flags){ return kmalloc_array(n, size, flags | __GFP_ZERO);}
kcalloc()
函數(shù)為數(shù)組分配內(nèi)存,大小n*size
,并對分配的內(nèi)存清零。該函數(shù)的最終實(shí)現(xiàn)類似kmalloc()
函數(shù)。
每次使用kcalloc()
后,都要有對應(yīng)的內(nèi)存釋放函數(shù)kfree()
。
舉例:
struct drm_clip_rect { unsigned short x1; unsigned short y1; unsigned short x2; unsigned short y2;};int drm_mode_dirtyfb_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv){ ... struct drm_clip_rect *clips = NULL; ... clips = kcalloc(num_clips, sizeof(*clips), GFP_KERNEL); ... kfree(clips); ...}
感謝各位的閱讀,以上就是“Linux內(nèi)核內(nèi)存分配函數(shù)kzalloc和kcalloc怎么使用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Linux內(nèi)核內(nèi)存分配函數(shù)kzalloc和kcalloc怎么使用這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。