Skip to content

Is dangling pointer dangerous if never being used?

An answer to this question on Stack Overflow.

Question

We have already known that use-after-free vulnerabilities could cause the security problems. Since the use-after-free error is born from dangling pointer, my question is that if the dangling pointers are not being used in a program, are they considered safe or benign(not such dangerous)?

Answer

Though you frame your question in terms of security and vulnerabilities, I think the more compelling reason to avoid avoid dangling pointers is to help programs fail early.

Setting pointers to NULL or nullptr when their referants are eliminated creates an easily-recognized error condition that is likely to cause failure as soon as the program tries to deference the pointer. Allowing the pointer to persist in refering to deallocated memory may cause difficult-to-debug conditions later.

In C++, unique_ptr, shared_ptr, and the like can help you avoid issues arising from dangling pointers.

In both C and C++, address sanitization can help you find memory abuses such as inappropriately deferenced pointers. In clang, gcc, clang++, and g++ you can use this tool by adding the -fsanitize=address flag to your compilation options (note it does not yet play well with multi-threading).