Tanner Summers
Tanner Summers

Reputation: 663

Deleting allocated array within function vs in main

If I declare a allocated pointer inside main

char *ch2=new char[10*17]; 
char *ch2p=ch2; 
while(infile.get(*ch2))
{
cout<<*ch2;
ch2++;
}
.................................
char *zc=rc.sortArray(ch2p,10,17);

inside the function I copy over the array into a new one that gets returned to main

T* a_ray = new T[(10*17)];
for(int i=0;i<rows;i++) 
{
    for(int j=0;j<cols;j++)
    {
        a_ray[i*cols+j] = arry[i*cols+j];
    }
}

Now my questions are, I added this into the function,

 delete [] arry; // delete old array

So I can delete the array created in main after copying it over into the new one that gets returned in main as zc look at code above but if I run a loop in main displaying the contents of the array, it shows all the contents as if the delete in function didn't work but when I deleted in main nothing shows up in loop so I assume it is deleted so,

1)my first question is why does deleting in function not work?

2)the line.

char *ch2p=ch2; 

is this a pointer to another pointer? and does this need to be deleted or do I jsut delete the ch2?

Thank you for any responses, also note this code is snippets from my class which is now over so I can't get answers to it.

Upvotes: 0

Views: 1476

Answers (2)

celeborn
celeborn

Reputation: 292

everywhere where you create a new array, you have to call delete. If you copied the array into a function, and you are going to use it after that please take into account that you have to have access to both arrays in meantime. That is necessary, because you need to know the starting cell of the copied data after the delition of the first array. Moreover, the pointers:

char *ch2p=ch2;

just points to the same memory in your case the first cell of the array ch2. Notice here that if you passed this pointer ch2p as an argument, and going to change or delete it, you have to pass it as a double pointer.

Upvotes: 2

It&#39;sPete
It&#39;sPete

Reputation: 5211

You do not need to call delete on ch2p. It's just a pointer, and points to allocated memory you created when calling new on ch2.

In terms of being able to access the array after calling delete... this is normal. You still have the address where the memory WAS found and all deleting did was free up that memory to the heap. If nothing has come by to claim it, the contents will remain unchanged.

Upvotes: 0

Related Questions