While declaring all c++ pointer, all should by default be initilized to ZERO or NULL to avoid any random unwanted values. So that we can check if pointer is null that means not initilized.
thanks
We can use nullptr to explicitly initialize or assign a pointer a null value. In the above example, we use assignment to set the value of ptr2 to nullptr , making ptr2 a null pointer. Use nullptr when you need a null pointer literal for initialization, assignment, or passing a null pointer to a function.
A null pointer is a pointer which points nothing. Some uses of the null pointer are: a) To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet. b) To pass a null pointer to a function argument when we don't want to pass any valid memory address.
free() is a library function, which varies as one changes the platform, so you should not expect that after passing pointer to this function and after freeing memory, this pointer will be set to NULL.
It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.
In C++03, prefer ptr = 0
over ptr = NULL
(Bjarne S. says that. Read the excerpt below quoted from his site)
In C++0x, ptr = nullptr
(see this)
Bjarne Stroustrup says that,
Should I use NULL or 0?
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's going to be called in C++0x. Then, "nullptr" will be a keyword.
void * ptr = NULL;
or
void * ptr = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With