Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this pointer initialization necessary?

Lets say I have the following:

 CHARLINK * _init_link(CHARLINK **link)
 {
    short i;
    (*link)->cl = (CHARLINK **) calloc(NUM_CHARS, sizeof(CHARLINK *));
    for (i = 0; i < NUM_CHARS; i++)
        (*link)->cl[i] = NULL;
    return (*link);
}

Is the loop to initialize each element to NULL necessary or are they automatically NULL from calloc?

like image 261
user318747 Avatar asked May 14 '10 20:05

user318747


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!

Do I need to initialize a pointer in C?

You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.

Why is it required to initialize pointer What happens if not?

It is necessary only when you expect it to have a default value. As pointers, just like other variables will hold garbage value unless it is initialized.

Is it essential to initialize null pointer?

Declaring and initializing a pointer is very essential as they work with the addresses of the memory directly.In this article, you will learn about the difference between the null pointer and the void pointer.


2 Answers

Yes, the assignment to NULL in the loop is necessary. calloc initialises to all bits 0. But a null pointer may not be represented like that. It is implementation dependent. Thus the assignment is necessary.

like image 109
Heidelbergensis Avatar answered Oct 20 '22 17:10

Heidelbergensis


That depends a bit on your system, but in the vast majority of cases it's ok. calloc() returns you a buffer filled with zeros. However, the null pointer on your machine might not be a bit pattern of 0. On a machine where the null pointer is non-zero, you might end up in trouble.

like image 42
Carl Norum Avatar answered Oct 20 '22 16:10

Carl Norum