Search code examples
c++pointersdynamicnew-operatordelete-operator

Why do I get an error deleting a dynamic pointer?


Please don't come and say "jUst read the error", it doesn't specify it, that's why Im asking here.

int main()
{
    int* p, * q;
    int a = 10;
    p = new int;
    p = &a;
delete p;
}

Solution

  • p = new int  
    

    In this line, you dynamically allocate the memory that you need to delete.

    p = &a
    

    But in this line, you are not allocating new memory, you are pointing p at stack memory, and leaking the memory that you previously allocated.