Kaustav Kaustav - 3 months ago 8
C Question

Why can't I initialize and declare pointer to pointer to NULL in C?

I wrote a C program. Some part of the code which is inside a function looks like this:

struct node* functionName(struct node *currentFirstPointer){
struct node **head = NULL;
*head = currentFirstPointer;
return *head;
}


Here
node
is a structure. But this line gives me a
segmentation fault
when I run the program. But if I declare and initialize the pointer to pointer in separate statements inside the same function like below then it works fine.

struct node* functionName(struct node *currentFirstPointer){
struct node **head;
*head = NULL;
*head = currentFirstPointer;
return *head;
}


What could be the reason that the 1st block doesn't work and the 2nd block works fine?

Answer

You have two examples of dereferencing a pointer.

struct node **head = NULL;
*head = currentFirstPointer;

and

struct node **head;
*head = NULL;
*head = currentFirstPointer;

Both are cause for undefined behavior. In the first, you are dereferencing a NULL pointer. In the second, you are dereferencing an uninitialized pointer.

The second block may appear to work but that's the problem with undefined behavior.

You need to allocate memory for head first before you can dereference the pointer.

struct node **head = malloc(sizeof(*head)*SOME_COUNT);
*head = currentFirstPointer;