"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Is it safe to delete null pointers in C++?

Is it safe to delete null pointers in C++?

Posted on 2025-05-01
Browse:133

Is Deleting a NULL Pointer in C   Safe?

Handling NULL Pointers in C : Safe Deletion

In C , it's crucial to understand the behavior of pointers, including NULL pointers. One common question arises: is it safe to delete a NULL pointer?

Is It Safe to Delete NULL Pointers?

Yes, it is safe to delete a NULL pointer. C 's delete operator performs a check before attempting to delete a pointer, regardless of its value. Therefore, attempting to delete a NULL pointer will not cause any undefined behavior.

Good Coding Style

However, checking for NULL pointers before deleting them is considered good coding style. This practice can help detect errors during development and prevent any potential issues related to double deletion.

Recommended Practice

A highly recommended practice is to set the pointer to NULL after deletion. This helps avoid double deletion and other similar memory corruption problems. For instance, consider the following code:

int* ptr = new int[10];
delete [] ptr; // Delete the array
ptr = NULL;    // Set the pointer to NULL

Advanced Consideration

In some cases, it can be desirable for the delete operator to automatically set the pointer to NULL after deletion. While C does not provide this by default, it's possible to achieve this behavior using a macro or a custom function.

For example, consider the following hypothetical macro:

#define my_delete(x) {delete x; x = NULL;}

Using this macro, the code from the previous example could be written as:

int* ptr = new int[10];
my_delete(ptr); // Delete the array and set ptr to NULL

By following these practices, developers can ensure safe and reliable pointer manipulation in C applications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3