Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sqlite memory leak on failed open #65

Closed
polesapart opened this issue Jan 4, 2017 · 2 comments
Closed

sqlite memory leak on failed open #65

polesapart opened this issue Jan 4, 2017 · 2 comments

Comments

@polesapart
Copy link

The sqlite::database constructor has a potential memory leak if opening the database fails for whatever reason:

database(std::u16string const & db_name): _db(nullptr) {
			sqlite3* tmp = nullptr;
			auto ret = sqlite3_open16(db_name.data(), &tmp);
			if(ret != SQLITE_OK) exceptions::throw_sqlite_error(ret);

			_db = std::shared_ptr<sqlite3>(tmp, [=](sqlite3* ptr) { sqlite3_close_v2(ptr); }); // this will close the connection eventually when no longer needed.

			//_db.reset(tmp, sqlite3_close); // alternative close. (faster?)
		}

accordingly to https://www.sqlite.org/c3ref/close.html one must close the handle even if open returned an error. The above can be fixed by moving the fail check and the exception throwing after defining the _db shared_ptr, so it will call sqlite3_close_v2 at stack unwinding. One can prefer to do an explicit close instead, which is cheaper but more verbose. I took the 1st approach, below:

database(std::u16string const & db_name): _db(nullptr) {
			sqlite3* tmp = nullptr;
			auto ret = sqlite3_open16(db_name.data(), &tmp);
			_db = std::shared_ptr<sqlite3>(tmp, [=](sqlite3* ptr) { sqlite3_close_v2(ptr); }); // this will close the connection eventually when no longer needed.
   			if(ret != SQLITE_OK) exceptions::throw_sqlite_error(ret);
			//_db.reset(tmp, sqlite3_close); // alternative close. (faster?)
		}
@aminroosta
Copy link
Collaborator

@polesapart As always thanks :-)

This should be fixed here aminroosta@b867b5e

@polesapart
Copy link
Author

Valgrind isn't complaining anymore, so I think we can close this :-) 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants