TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Pascal Schmidt
from: Bo Simonsen
date: 2004-01-27 21:09:58
subject: Re: [C] Question about external variable initialization

PS> Hi Bo! :-)

 BS> char* strdup(char* text)
 BS> {
 BS>         char* tmptext = NULL;

 BS>         if(text) /* if text is not NULL */
 BS>         {
 BS>                 tmptext = malloc(strlen(text)+1); 
 BS>                 /* allokate the lenght of text and 1 extra char for 
 BS> the 
 BS>                    string NULL termination */
 BS>                 strcpy(tmptext, text);
 BS>         }

 BS>         return tmptext;
 BS> }

 PS> Keep care that your strings are always 0-terminated, otherwise this
 PS> will run off the end of the string in strlen().

Yes the extra byte isn't nessersary after I did think of.

I get in a NULL terminated string:

H e l l o   W o r l d  \0   <- text + x
0 1 2 3 4 5 6 7 8 9 10 11   <- x

strlen will return 11. So there will be space for \0.

Gruss,
Bo



--- Maximus/UNIX 3.03b
* Origin: The Night Express - Roennede, Dk (2:236/100)
SEEN-BY: 633/267 270
@PATH: 236/100 237/9 20/11 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.