char *kstrndup(const char *s, size_t max, gfp_t gfp) 这个函数的作用和kstrlen的作用相同,但是它
限制了字符串的长度不能超过形参max
其源码分析如下:
/**
* kstrndup - allocate space for and copy an existing string
* @s: the string to duplicate
* @max: read at most @max chars from @s
* @gfp: the GFP mask used in the kmalloc() call when allocating memory
*
* Note: Use kmemdup_nul() instead if the size is known exactly.
*/
char *kstrndup(const char *s, size_t max, gfp_t gfp)
{
size_t len;
char *buf;
#形参s不能为null
if (!s)
return NULL;
#字符串的长度最大值为max。这里也就是取字符串长度和形参max的最小值
len = strnlen(s, max);
#申请buf,主要这里buf如果为null的话,整个函数也就返回为null了
buf = kmalloc_track_caller(len+1, gfp);
if (buf) {
memcpy(buf, s, len);
#字符串的结尾处添加结束符
buf[len] = '\0';
}
#返回buf,正常情况下这个buf中已经包含形参s中的内容了
return buf;
}
内存管理API之kstrndup
最新推荐文章于 2022-03-02 18:25:53 发布