-1

I was solving an online exercise related to de-allocating memory pointed to by pointer using delete keyword in C++. Following is my code.

#include<iostream>
#include<string>
#include<conio.h>

int main()
{
    double *ptrDouble = new double;
    *ptrDouble = 22;

    std::cout << "\nValue of ptrDouble = " << *ptrDouble << std::endl;

    delete ptrDouble;

    std::cout << "Value of ptrDouble = " << *ptrDouble << std::endl;

    getch();
}

So according to the online site where i am solving this exercise,

If you use the delete keyword on the pointer , the memory will be deallocated and therefore the contents will not be available to your application any longer. Attempting to access the contents will cause your application to crash due to a memory violation.

But when i try to print the value of the ptrDouble after deallocating the memory, the program doesn't crashes, instead a garbage value is printed on the console.

Question is, am i doing something wrong or that online site is wrong about whether program should crash or not ?

PS. I am using visual studio 2015 community.

  • 3
    The statement is plain wrong. Dereferencing a pointer to a deallocated memory region is undefined behavior. That can result e.g. in a crash, return a (apparently) garbage value oder it can return the last value stored there. – MikeMB Jan 01 '17 at 01:51
  • When you are doing stuff that has undefined behaviour anything is up for grabs – Ed Heal Jan 01 '17 at 01:51
  • 1
    Undefined behavior. It may crash, and may not – Danh Jan 01 '17 at 01:51

1 Answers1

1

Accessing freed memory leads to undefined behavior. Crashing or reading garbage both fall into that category. Whether or not the program will actually crash depends on whether that particular block of memory was returned to the OS or merely made available for reuse.

Joseph Artsimovich
  • 1,499
  • 10
  • 13