Why the below piece of code is not crashing , though i have deleted the object?

后端 未结 10 1332
北海茫月
北海茫月 2021-01-18 02:29
class object
{
  public:
    void check()
    {
      std::cout<<\"I am doing ok...\"<

        
10条回答
  •  长情又很酷
    2021-01-18 03:04

    1) Depends on compiler, on Mac OS with gcc 4.0.1:

    g++ -Wall -g -c main.cpp -o main.o
    g++ -o x main.o 
    ./x
    I am doing ok ...
    I am doing ok ...
    x(5857) malloc: *** error for object 0x100150: double free
    *** set a breakpoint in malloc_error_break to debug
    I am doing ok ...
    

    Double free is causing problems.

    2) Generally deleting pointer that has already been deleted is not defined, you should always set pointer to 0 after deleting, calling delete on pointer with value 0 is allowed.

    3) The reason it can still print the string is that the pointer still points to memory that was now freed, but I would assume that only the pointer is reclaimed e.g. returned to free pool for reuse, the memory is not overwritten or nulled so if you dereference the pointer you still get the original values, unless the memory is reused in the meantime.

提交回复
热议问题