If I create 2 pointers:
int *pointer;
int *temp;
and I allocate memory for one of them in this case temp
:
temp = new int [ size ]; //size = 6
I then point my second pointer pointer
to the same memory location:
pointer = temp;
If I want to deallocate temp:
delete [ ] temp;
it won’t let me… And I say it won’t let me because if I do a loop to populate elements of temp
it will still let me populate it even after I used delete [ ] temp;
. I am trying to understand what happens here so now my questions are:
- When I did
delete [ ] temp;
was the memory deallocated (I think not because I had another pointer pointing to that location) and if it wasn’t… does that means thedelete [ ] temp;
had no effect? - Is it possible to deallocate memory if more than one pointer is pointing to that memory location?
- Lets say that i am done with both pointers and I want to free the memory, what would be the best way to do it? I cannot do
delete [ ] pointers;
because I never allocated memory for pointer I just pointed it to thetemp
memory address.
Note: I know that I can use vectors I am just trying to understand memory management while using pointers.