Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it necessary to call pointer = NULL when initializing?

Tags:

c

pointers

alloc

when I create a pointer to certain struct, do I have to set it to NULL, then alloc it then use it? and why?

like image 645
user1051003 Avatar asked Sep 03 '12 19:09

user1051003


People also ask

Is it necessary to initialize a pointer?

All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer. Practice safe programming: Initialize your pointers!

Are pointers default initialized to null?

static variables are initialized to 0, which does the right thing for pointers too (i.e., sets them to NULL, not all bits 0). This behavior is guaranteed by the standard.

Are pointers automatically set to null?

In the absense of explicit initializations, external and static variables are guaranteed to be initialized to zero. So, yes.

Is the null pointer same as an initialise pointer?

A null pointer should not be confused with an uninitialized pointer: a null pointer is guaranteed to compare unequal to any pointer that points to a valid object. However, depending on the language and implementation, an uninitialized pointer may not have any such guarantee.


2 Answers

No, you don't have to set it to NULL, but some consider it good practice as it gives a new pointer a value that makes it explicit it's not pointing at anything (yet).

If you are creating a pointer and then immediately assigning another value to it, then there's really not much value in setting it to NULL.

It is a good idea to set a pointer to NULL after you free the memory it was pointing to, though.

like image 184
Levon Avatar answered Oct 06 '22 23:10

Levon


No, there is no requirement (as far as the language is concerned) to initialize a pointer variable to anything when declaring it. Thus

T* ptr;

is a valid declaration that introduces a variable named ptr with an indeterminate value. You can even use the variable in certain ways without first allocating anything or setting it to any specific value:

func(&ptr);
like image 43
eq- Avatar answered Oct 07 '22 00:10

eq-