[ILUG] C question [puzzled by strdup()]

From: Conor Daly (conor.daly at domain oceanfree.net)
Date: Thu 02 Aug 2001 - 09:29:12 IST


Just looking at Bob Stout's strdup() below:

/*
** Portable, public domain strdup() by Bob Stout
*/

#include <stdlib.h>
#include <string.h>

char *strdup(const char *string)
{
      char *new;

      if (NULL != (new = malloc(strlen(string) + 1)))
            strcpy(new, string);
      return new;
}

I do:

char *optionstring;

optionstring = strdup("first string");
optionstring = strdup("Second string that's longer than the first so \
malloc will use a different memory block");

The first call to strdup() allocates memory to hold the string and sets
optionstring to that address. When the second strdup() call passes a
*new* address to optionstring, what happens the previously allocated
memory that optionstring *was* pointing to?

Conor

-- 
Conor Daly <conor.daly at domain oceanfree.net>
Domestic Sysadmin :-)
---------------------
Faenor.cod.ie
 11:57pm  up 48 days, 16 min,  0 users,  load average: 0.00, 0.00, 0.00
Hobbiton.cod.ie
 12:00am  up 48 days, 36 min,  3 users,  load average: 0.00, 0.00, 0.00


This archive was generated by hypermail 2.1.6 : Thu 06 Feb 2003 - 13:11:26 GMT