Home > database >  If we assign a dynamically allocated pointer to another pointer, what happens?
If we assign a dynamically allocated pointer to another pointer, what happens?

Time:04-26

#include <iostream>
using namespace std;

int main()
{
    int* A = new int[2];
    A[0] = 10000;
    A[1] = 2;
    int*B = A;
    delete B;
    cout << B << A;
}

I found the code above, delete B; removes the data of array A. Can we remove allocated memory by free some another assigned pointer?

CodePudding user response:

You don't delete pointers. You delete the thing pointed to.

A, in your example isn't an array. It is a pointer that points to the first element of an array. When you write int* B = A;, you make B a pointer to the same memory. At that point A and B are identical, and the array they point to can be freed via either of them.

It doesn't matter how many times you copy a pointer. All that matters is that the thing pointed to by the pointer you pass wo your deletion expression was allocated with the corresponding allocation expression (i.e. new/delete, new[]/delete[], malloc/free, etc).

CodePudding user response:

Can we remove allocated memory by free some another assigned pointer?

Yes, as long as you do it correctly i.e., using the appropriate delete-expression.

From new.delete.single-12:

Requires: ptr shall be a null pointer or its value shall represent the address of a block of memory allocated by an earlier call to a (possibly replaced) operator new(std​::​size_­t) or operator new(std​::​size_­t, std​::​align_­val_­t) which has not been invalidated by an intervening call to operator delete.

This means that in your program, we are allowed to write:

delete [] B;

On the other hand delete B; is incorrect because we must use array-form of delete-expression here.

  •  Tags:  
  • c
  • Related