Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a pointer array without deleting the pointed objects in memory?

I would like to know if there is a way to delete a pointer array without touching the pointed objects in memory.

I'm writing a restriction routine for a HashSet I implemented a couple of days ago, so when the hash table is full it gets replaced by another double sized table. I'm representing the hash table using an array of pointers to an object (User), and the array itself is declared dynamically in my HashSet class, so it can be deleted after copying all its content to the new table using a hash function.

So basically I need to:

  1. Declare another table with a size that equals the double of the original array size.
  2. Copy every pointer to User objects from my original array to the new one applying my hash function (it gets the User object from memory and it calculates the index using a string that represents the user's name).
  3. After inserting all the pointers from the original array to the new one, I will have to free the allocated memory for the original array and replace the pointer in my HashSet class (member private userContainer) with the location of the new one (array).

The problem is that if I use delete[] userContainer to free the allocated memory for it, it will also delete every object in memory so the newly created replacement array will point to freed positions in memory!

like image 499
Youssef Khloufi Avatar asked Aug 04 '26 13:08

Youssef Khloufi


1 Answers

What you describe does not sound right.
Let's say you have a class A and you create an array of As with:

A** array1 = new A*[32];

Then fill it:

for(int i = 0; i < 32; ++i)
    array1[i] = new A();

Doing a delete[] array1 does not free the elements of array1.

So this is safe:

A** array1 = new A*[32];
for(int i = 0; i < 32; ++i)
    array1[i] = new A();

A** arary2 = new A*[64];
for(i = 0; i < 32; ++i)
   array2[i] = array1[i];

delete [] array1;

for(i = 0; i < 32; ++i)
    // do something with array2[i]
like image 128
esskar Avatar answered Aug 06 '26 03:08

esskar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!