> Okay. I have a class that the constructor sets default string values using
> strdup to copy the strings into the variables. This is mainly so that the
> destructor can call free for each variable without worrying about freeing
> unitialized memory. 
If you use C++, use new and delete operator. New() is superior than
malloc() because it guarantees that it will never return NULL (It will
throw exception if failed). Delete() is safer than free() because you
can delete NULL without raising run-time error (AFAIK).

>However, what happens when strdup is used a second
> time? i.e. the first statement is name = strdup( "Joseph" ) and the second
> statement is name = strdup( "Martin" ). What happens to the orginal memory
> name pointed to? Is it freed? Is it left there? What do I need to do (if
> anything)?
> 
C++ doesn't have garbage collection mechanism, so the original memory
will be left there until the process terminates. The 'clean' way to
prevent this is to wrap the string into a class, and override '='
operator so it deletes the current  string before assigning new string.

> Joseph
> 
- Benny LP

Reply via email to