Adam
Adam

Reputation: 10016

Trouble with fields initialized via pointer

My problem involves the following function:

/*Adds the transaction to the head of the linked list attached to the account.*/
void Bank::Worker::UpdateTransactionHistory(int account_number, string transaction, Bank *our_bank_ptr) {

    transaction_node new_trans;
    new_trans.transaction = transaction;

    if (our_bank_ptr->accounts[account_number].head == nullptr) {   //If this is the first transaction
        our_bank_ptr->accounts[account_number].head = &new_trans;

    } else {    //If this isn't the first transaction, disconnect the account from its current transaction list, connect the new transaction to the account and then connect the old list to the new transaction.
        transaction_node temp;
        temp = *(our_bank_ptr->accounts[account_number].head);

        our_bank_ptr->accounts[account_number].head = &new_trans;

        new_trans.next = &temp;
    }

if (our_bank_ptr->accounts[account_number].head) //here the correct string is printed
            cout << our_bank_ptr->accounts[account_number].head->transaction;
}

Its meant to update the transaction field of new_trans, which is then linked to the rest of the transaction list for a given account. Just before I return from the update transaction function I test to make sure the string was added in properly. The very last line of the function is cout << our_bank_ptr->accounts[account_number].head->transaction;,which outputs the transaction string correctly.

However, when I return from the function and immediately invoke the exact same line of code the compiler tells me that the transaction field the function updated still uninitialized. This is despite the fact that it was passed in as a pointer.

What the heck!? I thought that if I pass info into a function via pointers that anything I did to that info over the course of the function was permanent? What am I missing here?

Thank for your help,

Adam

Upvotes: 1

Views: 55

Answers (1)

You're setting the pointer to point to a local variable (new_trans). Once the function exits, this variable is destroyed and the pointer is dangling. So trying to dereference it results in Undefined Behaviour. In your case, this currently manifests as printing as unitialised. But it could do anything else.

If you need pointers there, and need them to point to persisting values, you'll have to allocate the values dynamically. But the real question is: do you need pointers?

Upvotes: 1

Related Questions