-2

After I searched about how to verify if a pointer is deleted in C++, i found out that there is no certain way, some really ugly work-around or smart pointers (I first want to understand how normal pointers works). My question is why C++ crashes when I try in a try/catch to show the value of a deleted pointer? shouldn't it handle the crash and just print the exception ??

void main()
{
    int *a = new int[5];

    for (int i = 0; i < 5; i++)
    {
        *(a + i) = i;
    }

    for (int i = 0; i < 5; i++)
    {
        if (*(a + i) != NULL) // useless verify, cuz if it would be NULL, it 
                              //would crash imediately
        {
            cout << (a + i) << ", " << *(a + i) << endl;
        }
    }

    delete a;
    cout << a << ", ";// << *a << endl;

    for (int i = 0; i < 5; i++)
    {
        try{
            cout << (a + i) << ", " << *(a + i) << endl;
        }
        catch (int e)
        {
            cout << "Error: " << e << endl;
        }
    }

    cin.get();
}
Andrei Bratu
  • 51
  • 1
  • 1
  • 10

3 Answers3

4
try{
        cout << (a + i) << ", " << *(a + i) << endl;
    }
    catch (int e)
    {
        cout << "Error: " << e << endl;
    }

You can catch an exception only if one is thrown. Accessing freed memory is Undefined Beahvior and does not throw an exception, so there is nothing to catch.

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
0

First for array deletion the syntax is delete [] a; secondly your try catch block is not for handling corrupted address, and unfortunate there is not exception handling for memory access violation in C++.

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
-1

There are no exception thrown in this case, simply undefined behavior. Exceptions are made to explicitly catch exceptions that are being thrown.

Also, use delete [] a; instead of delete a; to delete an array.

Also, when we delete memory, the memory does not actually get deleted but is free to be overwritten from now on.

What cout would print does not say much on whether the pointer was deleted.

Kostas
  • 4,061
  • 1
  • 14
  • 32