cpointersstructstaticglobal-variables

Static global pointer in struct.h is malloced by a function in struct.c, but it is NULL inside main()


struct.h

#ifndef STRUCT_H
#define STRUCT_H

struct linkedlist
{
    int data;
};

static struct linkedlist *head = NULL;

void build_linkedlist();
#endif

struct.c

#include <stdio.h>
#include <stdlib.h>
#include "struct.h"

void build_linkedlist()
{
    head = malloc(sizeof(struct linkedlist));
    head->data = 5;
    printf("inside build_linkedlist(): head = %p\n\n", head);
}

main.c

#include <stdio.h>
#include "struct.h"

int main()
{
    build_linkedlist();
    printf("inside main(): head = %p\n", head);
}

output

inside build_linkedlist(): head = 0x55ce669e62a0
inside main(): head = (nil)

Problem:

By calling build_linkedlist(), the head pointer is first allocated with an address, but when we access it in main(), its value is nil (I guess that means NULL).

How to resolve this?


Solution

  • Your header file contains static definitions for head and end_node. That means each source file that includes them gets its own copy of that variable. So head in main.c is a different variable than head in struct.c, and the same for end_node.

    If you want a variable to be visible in all translation units, you need to declare it the header without the static keyword:

    extern struct linkedlist *head, *end_node;
    

    And define it in exactly one source file:

    struct linkedlist *head = NULL, *end_node = NULL;