Search code examples
c++delete-operator

which amongst these two cases would result in memory leak


using delete:

int** a=new int*;
**a=5;
delete a;

using delete[]:

int** a=new int*;
**a=5;
delete[] a;

To find out, I tried doing this-

int** a=new int*;
**a=5;
int* b=new int;
b=*(a);
delete[] a;
cout<<"*b: "<<*b;

getting an output- 5

but I suspect that integer stored in b might have been deleted but not changed (no good reason to get a garbage value right ahead).

What should I do to find out (or what is the answer).


Solution

  • int** a=new int*;
    **a=5;
    delete a;
    

    This is wrong, because you allocate an int* and don't point it to an int afterwards. Accessing the int* itself via *a is OK, but accessing an int via the extra * is not OK. This is Undefined Behavior.

    You need to add that additional int, eg:

    int** a=new int*;
    *a = new int;  // <-- here
    **a = 5;       // <-- OK!
    delete *a;     // <-- and don't forget this!
    delete a;
    

    int** a=new int*;
    **a=5;
    delete[] a;
    

    Same problem as above - assigning to a non-existent int via **a - but worse because now you are also mismatching new and delete[]. More Undefined Behavior. You can use delete only with new, and delete[] only with new[].


    int** a=new int*;
    **a=5;
    int* b=new int;
    b=*(a);
    delete[] a;
    cout<<"*b: "<<*b;
    

    Now, that is just a culmination of bad behaviors. Not only are you:

    • assigning to a non-existent int via **a

    • mismatching new and delete[]

    But you are also:

    • leaking the int that you originally allocated for b to point to. You are re-assigning b afterwards with a new (invalid) int* value, losing access to the int you allocated. You have no hope of ever using a valid delete statement to free that int.

    • worse, you are dereferencing b to access an int after delete'ing the memory address stored in the int* that was assigned to b (and that int* was not valid to dereference to begin with).

    This code is just all kinds of Undefined Behavior.