Re: New/Delete and Malloc/Free in C++ code
Chris wrote:
> Does anyone know of or have experienced any problems with using
> new/delete and malloc/free in the same same C++ code base? Of course,
> not using free() on something you new'd.
>
> Specially, I tend to deal with C-strings a lot and when I want to
> make a copy I tend to use the strlen/new char[]/strncpy combination
> as in:
>
> // s1 may be on the stack or heap it is unknown to the authour
> // (i.e. returned for some library, etc.)
>
> s1 = "Some string";
>
> int n = strlen(s1);
> char *s2 = new char[n+1];
>
> strncpy(s2, s1, n);
> s2[n] = '\0';
>
> I would like to simplify this to simply:
>
> s1 = "Some string"; // same conditions on s1 as above
>
> char *s2 = strdup(s1);
>
> However, the implementation of strdup() that I use uses malloc to
> duplicate the string. Thus requiring me to use free() when I no
> longer want to use s2.
That's fine since the type is 'char'.
> So, could mixing new/delete and malloc/free in the same program cause
> problems? I'm thinking issues with the heap, etc.
Nope. Beyond the fact that 'strdup' is your own non-C++ function
which you use at your own risk, using new/delete (or new[]/delete[])
along with malloc/free is perfectly OK. Just don't use 'malloc'
for any non-POD types.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
|