lkml.org 
[lkml]   [2014]   [Jan]   [29]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
SubjectRe: [PATCH v4 1/2] mm: add kstrimdup function
From
Date
On Wed, 2014-01-29 at 19:58 -0500, Mikulas Patocka wrote:
> On Wed, 29 Jan 2014, Sebastian Capella wrote:
> > kstrimdup will duplicate and trim spaces from the passed in
> > null terminated string. This is useful for strings coming from
> > sysfs that often include trailing whitespace due to user input.
[]
> > diff --git a/mm/util.c b/mm/util.c
[]
> > /**
> > + * kstrimdup - Trim and copy a %NUL terminated string.
> > + * @s: the string to trim and duplicate
> > + * @gfp: the GFP mask used in the kmalloc() call when allocating memory
> > + *
> > + * Returns an address, which the caller must kfree, containing
> > + * a duplicate of the passed string with leading and/or trailing
> > + * whitespace (as defined by isspace) removed.
>
> It doesn't remove leading whitespace. To remove them, you need to do
>
> char *p = strim(ret);
> memmove(ret, p, strlen(p) + 1);
[]
> > + */
> > +char *kstrimdup(const char *s, gfp_t gfp)
> > +{
> > + char *ret = kstrdup(skip_spaces(s), gfp);
> > +
> > + if (ret)
> > + strim(ret);
> > + return ret;
> > +}
> > +EXPORT_SYMBOL(kstrimdup);

Why not minimize the malloc length too?

maybe something like:

char *kstrimdup(const char *s, gfp_t gfp)
{
char *buf;
const char *begin = skip_spaces(s);
size_t len = strlen(begin);

while (len && isspace(begin[len - 1]))
len--;

buf = kmalloc_track_caller(len + 1, gfp);
if (!buf)
return NULL;

memcpy(buf, begin, len);
buf[len] = 0;

return buf;
}




\
 
 \ /
  Last update: 2014-01-30 02:41    [W:0.138 / U:0.492 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site