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 :-)
{
    int64_t nNow = GetTime();
    int64_t start_time = GetTimeMillis();
    assert(reserver.isReserved());
    uint256 block_hash = start_block;
    ScanResult result;
    WalletLogPrintf("Rescan started from block %s...\n", start_block.ToString());
    fAbortRescan = false;
    ShowProgress(strprintf("%s " + _("Rescanning...").translated, GetDisplayName()), 0); 
    uint256 tip_hash;
    
    Optional<int> block_height = MakeOptional(false, int());
    double progress_begin;
    double progress_end;
    {
        auto locked_chain = chain().lock();
        if (Optional<int> tip_height = locked_chain->getHeight()) {
            tip_hash = locked_chain->getBlockHash(*tip_height);
        }
        block_height = locked_chain->getBlockHeight(block_hash);
        progress_begin = chain().guessVerificationProgress(block_hash);
        progress_end = chain().guessVerificationProgress(stop_block.IsNull() ? tip_hash : stop_block);
    }
    double progress_current = progress_begin;
    while (block_height && !fAbortRescan && !chain().shutdownRequested()) {
        m_scanning_progress = (progress_current - progress_begin) / (progress_end - progress_begin);