Merge pull request #224 from AI0867/wesnothd_memory_leak

Fix a memory leak in forum_user_handler
This commit is contained in:
Alexander van Gessel 2014-07-01 03:51:08 +02:00
commit d8aea90eaa
2 changed files with 21 additions and 6 deletions

View File

@ -115,7 +115,8 @@ bool fuh::user_exists(const std::string& name) {
// Make a test query for this username
try {
return mysql_fetch_row(db_query("SELECT username FROM " + db_users_table_ + " WHERE UPPER(username)=UPPER('" + name + "')"));
mysql_result res = db_query("SELECT username FROM " + db_users_table_ + " WHERE UPPER(username)=UPPER('" + name + "')");
return mysql_fetch_row(res.get());
} catch (error& e) {
ERR_UH << "Could not execute test query for user '" << name << "' :" << e.message << std::endl;
// If the database is down just let all usernames log in
@ -248,7 +249,13 @@ void fuh::set_lastlogin(const std::string& user, const time_t& lastlogin) {
}
}
MYSQL_RES* fuh::db_query(const std::string& sql) {
struct result_deleter {
void operator()(MYSQL_RES *result) {
mysql_free_result(result);
}
};
fuh::mysql_result fuh::db_query(const std::string& sql) {
if(mysql_query(conn, sql.c_str())) {
WRN_UH << "not connected to database, reconnecting..." << std::endl;
//Try to reconnect and execute query again
@ -258,11 +265,12 @@ MYSQL_RES* fuh::db_query(const std::string& sql) {
throw error("Error querying database.");
}
}
return mysql_store_result(conn);
return mysql_result(mysql_store_result(conn), result_deleter());
}
std::string fuh::db_query_to_string(const std::string& sql) {
return std::string(mysql_fetch_row(db_query(sql))[0]);
mysql_result res = db_query(sql);
return std::string(mysql_fetch_row(res.get())[0]);
}
@ -292,7 +300,8 @@ bool fuh::extra_row_exists(const std::string& name) {
// Make a test query for this username
try {
return mysql_fetch_row(db_query("SELECT username FROM " + db_extra_table_ + " WHERE UPPER(username)=UPPER('" + name + "')"));
mysql_result res = db_query("SELECT username FROM " + db_extra_table_ + " WHERE UPPER(username)=UPPER('" + name + "')");
return mysql_fetch_row(res.get());
} catch (error& e) {
ERR_UH << "Could not execute test query for user '" << name << "' :" << e.message << std::endl;
return false;

View File

@ -19,6 +19,7 @@
#include <vector>
#include <boost/shared_ptr.hpp>
#include <mysql/mysql.h>
// The [user_handler] section in the server configuration
@ -93,8 +94,13 @@ class fuh : public user_handler {
std::string db_name_, db_host_, db_user_, db_password_, db_users_table_, db_extra_table_;
// std::unique_ptr would be better, as the object isn't actually shared
// boost::scoped_ptr cannot be returned, so we can't use that
// TODO C++11: switch to std::unique_ptr
typedef boost::shared_ptr<MYSQL_RES> mysql_result;
// Throws user_handler::error
MYSQL_RES* db_query(const std::string& query);
mysql_result db_query(const std::string& query);
// Throws user_handler::error via db_query()
std::string db_query_to_string(const std::string& query);