diff --git a/ext/pg_connection.c b/ext/pg_connection.c index c8b71d67b..4243e674b 100644 --- a/ext/pg_connection.c +++ b/ext/pg_connection.c @@ -568,13 +568,16 @@ static VALUE pgconn_reset_start2( VALUE self, VALUE conninfo ) { t_pg_connection *this = pg_get_connection( self ); + /* Ensure conninfo is a valid C string before closing the connection. */ + char *p_conninfo = StringValueCStr(conninfo); /* Close old connection */ pgconn_close_socket_io( self ); PQfinish( this->pgconn ); + this->pgconn = NULL; /* Ensure no double free can happen. */ /* Start new connection */ - this->pgconn = gvl_PQconnectStart( StringValueCStr(conninfo) ); + this->pgconn = gvl_PQconnectStart( p_conninfo ); if( this->pgconn == NULL ) rb_raise(rb_ePGerror, "PQconnectStart() unable to allocate PGconn structure"); diff --git a/spec/pg/connection_spec.rb b/spec/pg/connection_spec.rb index fdae1b2b7..d9348c844 100644 --- a/spec/pg/connection_spec.rb +++ b/spec/pg/connection_spec.rb @@ -1871,6 +1871,11 @@ end.to raise_error(PG::Error) end + it "reset with invalid conninfo doesn't close the connection" do + expect{ @conn.send(:reset_start2, "\0") }.to raise_error(ArgumentError) + expect( @conn.exec("SELECT 1").values ).to eq([["1"]]) + end + it "closes the IO fetched from #socket_io when the connection is closed", :without_transaction do conn = PG.connect( @conninfo )