linux核心分配,Linux内核内存分配函数之kzalloc和kcalloc

本文介绍Linux内核内存分配函数:kzalloc()和kcalloc()。

一、kzalloc

文件: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()函数功能同kmalloc()。区别:内存分配成功后清零。

每次使用kzalloc()后,都要有对应的内存释放函数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;

...

}

二、kcalloc

文件: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()函数为数组分配内存,大小n*size,并对分配的内存清零。该函数的最终实现类似kmalloc()函数。

每次使用kcalloc()后,都要有对应的内存释放函数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核心分配)