Re: strtok and strtok_r



Charlie Gordon wrote:
"pete" <pfiland@xxxxxxxxxxxxxx> a écrit:

.... snip ...

Intsead of using realloc in a loop, I think most programmers
would write strdup with one function call to strlen and one to
malloc and one to strcpy.

Or more efficiently calling memcpy instead of strcpy.

char *strdup(const char *str) {
size_t len;
char *dest = NULL;

if (str) {
len = strlen(str);
dest = malloc(len + 1);
if (dest) {
memcpy(dest, str, len);
dest[len] = '\0';
}
}
return dest;
}

I challenge the 'more efficient'. It will be highly dependent on
the compiler, but at the simplest you would be trading the effort
of an extra procedure call against the possible efficiency
improvement. Since most strings are short (in my case, probably
under 10 or 20 chars) this 'improvement' is a chimera. Also
bearing in mind that strdup is a system reserved name, my version
(with a #include <stdlib.h>) is:

char *dupstr(const char *str) {
char *dest, *temp;

if (dest = malloc(1 + strlen(str))) {
temp = dest;
while (*temp++ = *str++) continue;
}
return dest;
}

and I am willing to let it go boom when str is NULL, for early
warning etc. of problems.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>



--
Posted via a free Usenet account from http://www.teranews.com

.



Relevant Pages

  • Re: strtok and strtok_r
    ... Or more efficiently calling memcpy instead of strcpy. ... char *strdup(const char *str) { ... char *dest = NULL; ...
    (comp.lang.c)
  • [BK PATCH] One strdup() to rule them all
    ... One strdup() to rule them all. ... -static inline char *kstrdup(const char *str) ...
    (Linux-Kernel)
  • Re: strtok and strtok_r
    ... char *t; ... Assignment as an test expression is considered sloppy and error prone. ... char *my_strdup(const char *str) { ... char *dest = NULL; ...
    (comp.lang.c)
  • Re: strtok and strtok_r
    ... char *strdup ... Adding useful functions like strdup ... char *strdup(const char *str) { ... char *dest = NULL; ...
    (comp.lang.c)
  • Re: strtok and strtok_r
    ... char *strdup ... Adding useful functions like strdup ... char *strdup(const char *str) { ... char *dest = NULL; ...
    (comp.lang.c)