Re: strtok and strtok_r
- From: CBFalconer <cbfalconer@xxxxxxxxx>
- Date: Sat, 15 Sep 2007 12:00:04 -0400
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
.
- Follow-Ups:
- Re: strtok and strtok_r
- From: Charlie Gordon
- Re: strtok and strtok_r
- References:
- strtok and strtok_r
- From: siddhu
- Re: strtok and strtok_r
- From: CBFalconer
- Re: strtok and strtok_r
- From: Charlie Gordon
- Re: strtok and strtok_r
- From: Martien verbruggen
- Re: strtok and strtok_r
- From: Charlie Gordon
- Re: strtok and strtok_r
- From: Sam Harris
- Re: strtok and strtok_r
- From: Charlie Gordon
- Re: strtok and strtok_r
- From: pete
- Re: strtok and strtok_r
- From: Charlie Gordon
- strtok and strtok_r
- Prev by Date: Re: tryick use of sizeof again[Explaination Wanted]
- Next by Date: Re: strtok and strtok_r
- Previous by thread: Re: strtok and strtok_r
- Next by thread: Re: strtok and strtok_r
- Index(es):
Relevant Pages
|