While checking #16661 I stumbled upon what seems to be a lifetime issue in `ReleaseWallet(CWallet* wallet)` (`wallet.cpp`).

https://github.com/bitcoin/bitcoin/blob/fa6431055abfacea4f72ef11d061c7c755de327a/src/wallet/wallet.cpp#L107-L111

After `delete wallet;` the pointer is invalid and shouldn't be used like in the call `g_unloading_wallet_set.erase(wallet)`.

The code was introduced in #14941 which was merged into `master` on January 15, 2019.

In addition to fixing this specific instance it might be worth thinking about how we can use static analysis to automatically catch this class of issues going forward :-)
walletInstance->WalletLogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
            nMaxVersion = FEATURE_LATEST;
            walletInstance->SetMinVersion(FEATURE_LATEST); 
        }
        else
            walletInstance->WalletLogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
        if (nMaxVersion < walletInstance->GetVersion())
        {
            chain.initError(_("Cannot downgrade wallet").translated);
            return nullptr;
        }
        walletInstance->SetMaxVersion(nMaxVersion);
    }
    
    if (gArgs.GetBoolArg("-upgradewallet", false)) {
        LOCK(walletInstance->cs_wallet);
        
        int max_version = walletInstance->GetVersion();
        if (!walletInstance->CanSupportFeature(FEATURE_HD_SPLIT) && max_version >= FEATURE_HD_SPLIT && max_version < FEATURE_PRE_SPLIT_KEYPOOL) {
            chain.initError(_("Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use -upgradewallet=169900 or -upgradewallet with no version specified.").translated);
            return nullptr;
        }
        bool hd_upgrade = false;
        bool split_upgrade = false;
        if (walletInstance->CanSupportFeature(FEATURE_HD) && !walletInstance->IsHDEnabled()) {
            walletInstance->WalletLogPrintf("Upgrading wallet to HD\n");
            walletInstance->SetMinVersion(FEATURE_HD);
            
            CPubKey masterPubKey = walletInstance->GenerateNewSeed();
            walletInstance->SetHDSeed(masterPubKey);