Skip to content

Commit 59b87a2

Browse files
author
John Newbery
committed
[wallet] Fix potential memory leak in CreateWalletFromFile
Fix proposed by ryanofsky in bitcoin#12647 (comment)
1 parent 13da289 commit 59b87a2

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/wallet/wallet.cpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4012,7 +4012,10 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
40124012

40134013
int64_t nStart = GetTimeMillis();
40144014
bool fFirstRun = true;
4015-
CWallet *walletInstance = new CWallet(name, WalletDatabase::Create(path));
4015+
// Make a temporary wallet unique pointer so memory doesn't get leaked if
4016+
// wallet creation fails.
4017+
auto temp_wallet = MakeUnique<CWallet>(name, WalletDatabase::Create(path));
4018+
CWallet* walletInstance = temp_wallet.get();
40164019
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
40174020
if (nLoadWalletRet != DBErrors::LOAD_OK)
40184021
{
@@ -4224,7 +4227,6 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
42244227
}
42254228

42264229
walletInstance->m_last_block_processed = chainActive.Tip();
4227-
RegisterValidationInterface(walletInstance);
42284230

42294231
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
42304232
{
@@ -4290,6 +4292,10 @@ CWallet* CWallet::CreateWalletFromFile(const std::string& name, const fs::path&
42904292
}
42914293
}
42924294
}
4295+
4296+
// Register with the validation interface. It's ok to do this after rescan since we're still holding cs_main.
4297+
RegisterValidationInterface(temp_wallet.release());
4298+
42934299
walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
42944300

42954301
{

0 commit comments

Comments
 (0)