Assigning freed memory value in C ++

I am learning C ++ using tutorials from http://www.learncpp.com . The lesson Dynamic memory allocation with new and delete ( http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/ ), it says:

Similarly, when a dynamically allocated variable is deleted, the pointer pointing to it is not null. Consider the following snippet:

int *pnValue = new int;
delete pnValue; // pnValue not set to 0

if (pnValue)
    *pnValue = 5; // will cause a crash

However, when I try it (compiler: GNU GCC compiler, ubuntu), my program does not crash.

int *pnValue = new int;
delete pnValue; // pnValue not set to 0
if (pnValue)
    *pnValue = 5; // will cause a crash -> doesn't
std::cout << "Did not crash" << std::endl;

What's going on here? Is there any form of checking runtime in C ++?

+4
source share
3 answers

, ( , @user1320881, , ). , undefined, ( ). - , , , , .

+9

undefined ++. , , ++ Super-FAQ . , , .

+2

EDIT: - - , , - undefined.

++ NULL ,, - , , .

, NULL , , , .

, , . , , , .

++ - .

, , , .

The C ++ compiler does not notice this , and also does not provide reference counting at runtime for objects allocated by memory, and does not check the operability of links at runtime. The compiler is just happy that you assigned the variable of the correct type to the memory referenced by

With C ++, allocating memory is not only difficult to handle, but it can also cause very serious problems. This is why reference counting is good practice, and it can also be used with C ++ with libraries allocated to it.

+1
source

All Articles