Why doesn't deleting my pointer delete my pointer?

前端 未结 8 1616
悲哀的现实
悲哀的现实 2021-02-13 04:22

So to understand new/delete better (really to prove to myself with small examples why virtual destructors are needed for interfaces), I want to understand memory leaks, so that

相关标签:
8条回答
  • 2021-02-13 05:20
    // Reserve some memory for an int and set that memory to the value 43.
    int* P1 = new int(43);
    
    // Print the address of the reserved memory.
    cout<<"P1 = "<<P1<<endl;
    // Print the contents of that memory.
    cout<<"*P1 = "<<*P1<<endl;
    
    // Free the memory - it is no longer reserved to you.
    delete P1;
    
    // int* P2 = new int(47);    
    
    // Print the address of the memory. It still holds the address to 
    // the memory that used to be reserved for you.
    cout<<"P1 = "<<P1<<endl;
    
    // Print the current value of the memory that used to be reserved.
    cout<<"*P1 = "<<*P1<<endl;
    

    If you would uncomment the P2 line, it is quite likely that it would be assigned the same memory which would change the value printed at the last line.

    Accessing memory that has been freed with delete causes undefined behaviour as others have pointed out. Undefined includes crashing in strange ways on some cases (only during full moon perhaps? ;-). It also includes everything working perfectly well for now, but with the bug being a mine that can trip off whenever you make another change anywhere else in your program.

    A memory leek is when you allocate memory with new and never free it with delete. This will usually not be noticed until someone runs your program for a longer period and finds out that it eats all the memory of the system.

    0 讨论(0)
  • 2021-02-13 05:21

    The memory is freed but it is not cleaned. The value may stay in memory until some other process writes a new value in that location.

    0 讨论(0)
提交回复
热议问题