Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c++ - How to detect if a pointer was deleted and securely delete it?

In C++ How to decide or know if a pointer was deleted before??

when i tried to delete a pointer that was previously deleted in another part of the code it threw an exception that can't be handled.

I was wondering if there is a way to check or try delete the pointer ? any reference about advanced memory operations.

also i want to master the un-handled exceptions of pointers and the access to protected or access is violation ,... this kind of error.

thanks for those who give some of their knowledge and their time to help other people and share their benfits


Update

The big advice from a lot of modern c++ developers community is - Use smart pointers or try to avoid the use of raw pointers. But for throw security and insuring free of memory (ISO_CPP_FAQ) and of course if you want to avoid the small overhead of using smart pointers[may not be noticeable always but they have overhead] you can write your custom methods that deal with raw pointers [type*] - this is not general. Prefer always smart pointers to raw pointers.

In 'Going Native 2013' a common advice given was - Never use raw pointers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There can be three solutions. You might want to choose one depending on the effort/quality ratio you want to acheive:

Elegant and most correct solution:

Use smart pointers and you do not have to manually call delete ever again. This is the best possible way to overcome this problem. It utilizes the principle of RAII which works perfectly for a language like C++ which does not have an in-built garbage collector.

Less elegant but workable solution:

Assign the pointer to NULL after deletion. Calling delete on a NULL pointer is a no-op so it removes the need to have that extra NULL check but this might hide some problems instead of making them visible.

Less elegant but more correct solution:

Hunt down all the multiple delete problems by letting your program crash. You might as well use memory analyzer programs like valgrind and then fix your code to avoid all these problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...