C (207/254)

From:Ray A. Akey
Date:24 Apr 00 at 04:13:55
Subject:Re: strdup()

Mike Carter <mike.carter@redhotant.co.uk> wrote:
> At a guess :) it duplicates a string? I'm trying to compile someone
> elses source, Jespers TManager GUI to be exact! :)
>
> If I allocate mem for my string in a function it would be deallocated
> on exit of the function , no? confused?

strdup() duplicates the given string. It does so, typically, using
malloc(). This means that YOU must free the returned string (memory) when
you are done with it. Failure to do so will result in a memory leak.

So, yes, you can imitate strdup() by allocating memory in a function as
follows:

/*
* purpose: duplicate the given string. caller must free the memory returned
by this function before exiting app.
* returns: NULL on error; pointer to valid memory (copy of string)
otherwise.
*/
char *mystrdup(const char *str)
{
char *dup = NULL;
if( (dup=malloc(strlen(str+1)) )
strcpy(dup, str);
return dup;
}

------------------------------------------------------------------------
You can win $1000 at eGroups!
Time-limited offer. Enter today at:
http://click.egroups.com/1/2863/1/_/451227/_/956546079/
------------------------------------------------------------------------