Re: delete[] or delete or delete[] * ???

From: Jakob Bieling (netsurf_at_gmy.net)
Date: 03/31/04


Date: Wed, 31 Mar 2004 09:57:36 +0200


"pembed2003" <pembed2003@yahoo.com> wrote in message
news:db593abd.0403302323.591608e5@posting.google.com...
> Hi,
> I have function that allocates a bunch of char* like:
>
> int stuffIt(char*** s){
> *s = new char*[3];
> **s = new char[4];
> *(*s+1) = new char[4];
> *(*s+2) = new char[4];
> **s = "abc";
> *(*s+1) = "123";
> *(*s+2) = "yyy";

    The above three lines do not do what you think they do. "**s" is of type
"char*", so the only thing you can assign to it is .. a char*! So '**s =
"abc";' assigns a char* that points to the string literal "abc", thus
overwriting the pointer to the newly allocated memory block. Btw, the string
literal "abc" is const and should never be assigned to a non-const char*!

> return 3;
> }
>
> It's call like:
>
> char** stuff;
> int size = stuffIt(&stuff);
>
> I then verify it with:
>
> for(int i = 0; i < size; i++){
> cout<<stuff[i]<<endl;
> }
>
> which correctly prints out "abc","123","yyy" but how do I delete the
> allocated memory when I am done? I try:
>
> delete[] stuff; // doesn't generate any error
>
> which only deletes the 3 char* but doesn't actually delete each
> individual char* right? So I tried delete each one by saying:
>
> for(int j = 0; j < size; j++){
> delete[] stuff[j];
> }
>
> but that generate a bunch of errors. I also tried something like:

    What kind of errors?

> delete stuff[j];
> delete [] *(*stuff+j);
> delete [] stuff+j;
> delete [] (*stuff+j);
>
> but none of them work. Any idea?

    Follow this rule: whatever you allocate with new must be freed with
delete and whatever you allocate with new[] must be freed with delete[]. So
in your case, you should free your arrays like this:

    delete [] **s;
    delete [] *(*s+1);
    delete [] *(*s+2);
    delete [] *s;

    Other than that, I would suggest you use the std::string and std::vector
classes. They handle the allocation and a lot more for you.

hth

--
jb
(replace y with x if you want to reply by e-mail)