Click to See Complete Forum and Search --> : freeing char* 's


gecka
September 17th, 2006, 09:37 AM
Hi! I need your opinion. Will this function free memory of all of the strings passed in as arguments?

void FreeString(int nArgs,...)
{
va_list ap;
va_start(ap,nArgs);

char* str = NULL;
for(int i=0;i<nArgs;i++)
{
str = va_arg(ap,char*);
if(str != NULL)
{
delete[] str;
str = NULL;
}
}
str=NULL;

va_end(ap);
return;
}

wildfrog
September 17th, 2006, 01:14 PM
Will this function free memory of all of the strings passed in as arguments?Yes, but... it will attempt to cast and free anything that's in the argumentlist.

Here is a more typesafe FreeString:

class FreeString
{
public:
FreeString() { }
friend const FreeString& operator << (const FreeString& lhs, char* rhs);
};

const FreeString& operator << (const FreeString& lhs, char* rhs)
{
delete[] rhs;
return lhs;
}

int main()
{
char* psz = new char[1024];
char* psz2 = new char[1024];

FreeString() << psz << psz2;

return 0;
}

Remember that strings are allocated in different ways. Some use new char[] and should be deleted using delete[], c-string functions (strdup) use malloc and should be deleted using free...

- petter