Permalink
Browse files

Memory cleanup in case of construction error

  • Loading branch information...
1 parent 0afd864 commit 3d7da33a147278381781c5c4f4d59e3dd107f2a6 @mariano committed Jun 3, 2011
Showing with 32 additions and 21 deletions.
  1. +31 −21 src/result.cc
  2. +1 −0 src/result.h
View
@@ -76,37 +76,47 @@ node_db_mysql::Result::Result(MYSQL* connection) throw(node_db::Exception&)
previousRow(NULL),
nextRow(NULL) {
this->result = mysql_store_result(this->connection);
- if (result == NULL && mysql_field_count(this->connection) != 0) {
- throw node_db::Exception(mysql_error(this->connection));
- } else if (result != NULL) {
- this->empty = false;
-
- MYSQL_FIELD* fields = mysql_fetch_fields(this->result);
- if (fields == NULL) {
- throw node_db::Exception("Could not buffer columns");
- }
- this->totalColumns = mysql_num_fields(this->result);
- if (this->totalColumns > 0) {
- this->columns = new Column*[this->totalColumns];
- if (this->columns == NULL) {
- throw node_db::Exception("Could not allocate storage for columns");
+ try {
+ if (result == NULL && mysql_field_count(this->connection) != 0) {
+ throw node_db::Exception(mysql_error(this->connection));
+ } else if (result != NULL) {
+ this->empty = false;
+
+ MYSQL_FIELD* fields = mysql_fetch_fields(this->result);
+ if (fields == NULL) {
+ throw node_db::Exception("Could not buffer columns");
}
- for (uint16_t i = 0; i < this->totalColumns; i++) {
- this->columns[i] = new Column(fields[i]);
- if (this->columns[i] == NULL) {
- delete [] this->columns;
- throw node_db::Exception("Could not allocate storage for column");
+ this->totalColumns = mysql_num_fields(this->result);
+ if (this->totalColumns > 0) {
+ this->columns = new Column*[this->totalColumns];
+ if (this->columns == NULL) {
+ throw node_db::Exception("Could not allocate storage for columns");
+ }
+
+ for (uint16_t i = 0; i < this->totalColumns; i++) {
+ this->columns[i] = new Column(fields[i]);
+ if (this->columns[i] == NULL) {
+ this->totalColumns = i;
+ throw node_db::Exception("Could not allocate storage for column");
+ }
}
}
- }
- this->nextRow = this->row();
+ this->nextRow = this->row();
+ }
+ } catch(...) {
+ this->free();
+ throw;
}
}
node_db_mysql::Result::~Result() {
+ this->free();
+}
+
+void node_db_mysql::Result::free() throw() {
if (this->columns != NULL) {
for (uint16_t i = 0; i < this->totalColumns; i++) {
delete this->columns[i];
View
@@ -47,6 +47,7 @@ class Result : public node_db::Result {
bool empty;
char** row() throw(node_db::Exception&);
+ void free() throw();
private:
MYSQL* connection;

0 comments on commit 3d7da33

Please sign in to comment.