Get the App
SLTechnology News&Howtos  ›  Development  › 

Is it appropriate for C++ to initialize null pointers with NULL?

Shulou Source: shulou.com Published: 2022-05-31 17:17:09 09月22日 Update

This article introduces the knowledge of "is it appropriate for C++ to initialize null pointers with NULL?". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Null pointer in 1.C++98

We know that in good Cmax programming habits, it is best to assign an appropriate initial value to a variable when declaring it, otherwise unexpected errors may occur.

The danger of the pointer

When you create a pointer in C++, the computer allocates memory to store the address, but not memory to store the data the pointer points to. It is a separate step that provides space for the data, and ignoring this step is undoubtedly asking for trouble, as shown below:

Int* fellow;*fellow = 1234

Fellow is indeed a pointer, but where does it point? The above code does not assign an address to fellow, so in which memory unit will 1234 be placed? We don't know. There is a fellow that has not been initialized, it may have any value. Whatever the value is, the program interprets it as an address that stores 1234. But if the value of fellow happens to be 1000, the computer will put the data on address 1000, even if this happens to be the address of the program code, and the fellow is probably not pointing to the 1234 that you want to store, and this error can lead to some of the most hidden and difficult to track bug.

So in order to avoid this problem, we all need to initialize the pointer. This is how we usually initialize the pointer.

Int main () {/ / Null pointer definition int* p1 = NULL; int* p2 = 0; return 0;}

NULL is actually a macro, and we can see the following code in the traditional C header file (stddef.h):

As you can see, NULL may be defined as a literal constant of 0 or a constant defined as an untyped pointer (void*). No matter what definition you take, you will inevitably encounter some trouble when using a pointer with a null value. For example: what is the output of the following code?

Void f (int) {cout

Tags: Pointers results code addresses constants storage suitability clocking memory pointing data programs problems identity keywords keywords content functions variables places Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Shulou Tech Info vpn Huawei MySQL