简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM