Why to avoid uninitialized pointers?

Why to avoid uninitialized pointers?

In day-to-day life, as a C++ developer using pointers is very common. But improper use of pointers may lead to severe problems. One such use case is uninitialized pointers.

What is uninitialized pointer?

No alt text provided for this image



Why uninitialized pointers are dangerous?

Uninitialized pointers mostly lead to run time crashes. It is also observed that uninitialized pointers and variables can cause run time crashes in release mode but a similar is not observed in debug mode. Such issues are hard to track down for a developer.

Let us dive into the topic to understand the reason behind the run time crash.

Under most of the compilers, if we use an uninitialized pointer then it will use whatever bits are in the memory in which pointer resides as if it were an address (pointing to some random location). When we try to manipulate the underlying data at such random location then it usually leads to the crash as soon as we attempt to dereference the uninitialized pointer. This can be easily understood from following diagram:

No alt text provided for this image

Difficulties associated with uninitialized pointers:

  • There is no way to distinguish a valid pointer from an address formed from the bits that are in the memory in which the pointer was allocated.
  • While programming, we generally use following if condition to avoid query data on nullptr:

No alt text provided for this image

  • But above if condition cannot save us from uninitialized pointers as they have some random address and will enter inside if condition.
  • In debug mode the variables are usually initialized to some compiler defined constant but same does not happen in release mode, that may be one of the reasons why sometimes uninitialized pointers may lead to crash in release mode that is not reproducible debug mode.

Pursottam Sah

SWE-1 @UKG | Ex- Full Stack Developer @AI4Bharat | Frontend Developer @Uniflik Pvt Ltd | Ex - SDE @Indian Oil | GDSC Open Source Lead | NIT AP CSE'24 | TnP Volunteer

1 年

Well written sir Rohit Kumar Sharma Sir I have messaged for could you please check your DM actually it's very important for me ????

回复
Dipayan Banerjee

Senior Software Development Engineer (Meshing and Geometry) | C++ Developer | Computer Graphics | Data Structures And Algorithms | Low Level Design

2 年

A very well written article, Please do write such interesting and cute concepts more often

要查看或添加评论,请登录

社区洞察

其他会员也浏览了