0

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 :-(

4
  • While compiling doesn't it complain with redeclaration error of Database inside if ? Commented Nov 7, 2013 at 13:16
  • No compilation errors, just bugs while running the code :-) Commented Nov 7, 2013 at 13:21
  • @@Danielbm Look at this output Commented Nov 7, 2013 at 13:27
  • Ok, the second declaration is under block scope of if statement. Commented Nov 7, 2013 at 14:39

1 Answer 1

12

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));
Sign up to request clarification or add additional context in comments.

1 Comment

never cast the result of malloc() please

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.