Danielbm
Danielbm

Reputation: 3

Struct pointer becomes NULL ? (C)

I'm new to C and I'm writing a code that does actions on a linked list. Here are some additional info before I add the code:

typedef struct Ticket Ticket;
    struct Ticket 
    {
        TTransaction *INFO;
        Ticket* next;
        Ticket* prev;
};

and my problematic code:

void HANDLER1(TTransaction* New_node)
{
    Ticket * Database;
    if(!DB_Manager_Initialize)
    {
        Ticket * Database =(Ticket*)malloc(sizeof(Ticket));
        if(!Database)
        {
            OutputMgr_ReportTransaction(AXN_FAILURE,NULL);
            IM_END_OF_INPUT1(Database);
            exit(EXIT_FAILURE);
        }
        Database->next=NULL;
        Database->prev=NULL;
        Database->INFO=NULL;
        DB_Manager_Initialize=1;
    }
    switch(New_node->Operation)
    {
        case(IM_CREATE):
                IM_CREATE1(New_node,Database);
        case(IM_UPDATE):
                IM_UPDATE1(New_node,Database);
        case(IM_RETRIEVE):
                IM_RETRIEVE1(New_node,Database);
        case(IM_DELETE):
                IM_DELETE1(New_node,Database);
        case(IM_END_OF_INPUT):
                IM_END_OF_INPUT1(Database);
    }
}

at first i just initialize "Database", mallocing it and setting its values to NULL. before the switch function, what i have is exactly what i expect: Database being a pointer to a Ticket type struct, and next,prev,info are pointers to NULL.

using variable watch in Visual i noticed that Database itself becomes a NULL pointer once i enter the switch function, I have no idea why.

New_node is a "TTransaction" type struct containing 2 chars, 2 ints and 1 ENUM (Operation).

Help :-(

Upvotes: 0

Views: 921

Answers (1)

Arjen
Arjen

Reputation: 646

This is because the first Database is shadowed by the second. Replace:

Ticket * Database;
if(!DB_Manager_Initialize)
{
    Ticket * Database =(Ticket*)malloc(sizeof(Ticket));

By:

Ticket *Database;
if(!DB_Manager_Initialize)
{
    Database = malloc(sizeof(Ticket));

Upvotes: 12

Related Questions