Deleting C++ pointers to an object

前端 未结 9 1182
攒了一身酷
攒了一身酷 2021-01-26 20:06

I thought that the delete command would free up memory I allocated. Can someone explain why it seems I still have the memory in use after delete?

class Test
{
pu         


        
相关标签:
9条回答
  • 2021-01-26 20:25

    Dereferencing a pointer to an object that has been deleted is undefined. The memory for that object probably hasn't been overwritten yet so your object is still there (If it works at all).

    0 讨论(0)
  • 2021-01-26 20:29

    Pointers are a container for an address in memory. You can always use a declared pointer, but unless it's initialized to memory that you own, expect confusion and worse.

    Test *e;
    e->time = 2;
    

    also compiles and won't work. Minimize this type of confusion so:

    {
      boost::scoped_ptr<Test> e(new Test);
    
      e->time = 1;
      cout << e->time << endl;
    
      e->time = 2;
      cout << e->time << endl;
    }
    

    No new/delete needed, just enclosing braces to define the scope, and an appropriate smart pointer.

    0 讨论(0)
  • 2021-01-26 20:29

    run it under valgrind. it will tell you that you did a bad thing

    0 讨论(0)
  • 2021-01-26 20:35

    As others have said, what you've done is wrong, but you can't expect any particular behavior.

    What's probably happening on most modern systems is the memory allocated for and occupied by e is on a memory page mapped as valid for your program, and the fact that you have deleted e, doesn't not undo that mapping.

    So you are still accessing memory that your application has permission to use from OS. Thus, no segmentation fault. It is possible, however that if enough things happen between delete e and accessing that memory the page will have been remapped. Then you get a seg fault.

    0 讨论(0)
  • 2021-01-26 20:40

    When you "delete" memory, you are basically returning the allocated memory back to the heap. This just means that the data structure used to organize heap memory is updated to indicate that the memory is now available to use. It is not cleared out or anything like that. You are accessing memory that still exists, but belongs to the operating system at this point. This is undefined behavior.

    EDIT:

    And by the way, a seg fault occurs when you try to read memory from a segment that you do not have read permissions for. In a flat memory model this probably means you tried to read memory in kernel space; probably because you dereferenced a bad pointer.

    0 讨论(0)
  • 2021-01-26 20:41

    I expected a seg-fault after e->time = 2;

    You shouldn't "expect" anything to happen; you are invoking undefined behavior, which by definition is, well, undefined. That means that you can no longer make any reasonable expectations about the state of your program.

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