简体   繁体   中英

Where am I dereferencing a NULL pointer?

there is the def of the Hash Table

typedef struct pair
{
    char* key;
    int value;
}pair;

typedef struct node
{
    pair* p;
    struct node* next;
}node;

node* hash_table[HASH_SIZE];    /*pointer to Hash Table*/

and there is the implemented of init_data

void init_data()
{
    int i;
    for (i = 0; i < HASH_SIZE; i++)
    {
        hash_table[i]->p = (pair*)malloc(sizeof(pair));
        if (hash_table[i]->p == NULL)
            printf("Error: in index %d ", i);

        hash_table[i]->p->key = NULL;
        hash_table[i]->p->value = 0;
    }

    curr_size = 0;
}

and the compiler send me a this message de - referencing NULL pointer why?

MatheusPortela has already discussed the problem in the comments. Here is the solution:

After declaring node* hash_table[HASH_SIZE];

Allocate memory for hash_table[i] :

for (int i = 0; i < HASH_SIZE; ++i)
{
    hash_table[i] = (node*)malloc(sizeof(node));
}

This should remove the segmentation fault. But you can also build the connections between the nodes ( next ) inside that loop.

In the code provided, hash_table is an array of node* . The array itself hash_table is initialized but its elements hash_table[i] (of type node* ) haven't. Then, de-referrencing with hash_table[i]->p raises an error since hash_table[i] is NULL .

You probably want to do some initialization of hash_table before actually using it. Something like this should do the trick:

for (int i = 0; i < HASH_SIZE; i++) {
    hash_table[i] = (node*)malloc(sizeof(node));
    if (i > 0)
        hash_table[i-1]->next = hash_table[i];
}

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