Skip to content

Commit

Permalink
Free URI with destruction of client to avoid mem leaks
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin Nowack committed Oct 23, 2018
1 parent 26df60d commit c58adfe
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/client.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ SEXP R_mongo_client_new(SEXP uri_string, SEXP pem_file, SEXP pem_pwd, SEXP ca_fi
if (!uri)
Rf_error("failed to parse URI: %s (%s)", uri_string, err.message);

SEXP uri_ptr = uri2r(uri);

mongoc_client_t *client = mongoc_client_new_from_uri (uri);
if(!client)
stop("Invalid uri_string. Try mongodb://localhost");
Expand Down Expand Up @@ -64,5 +66,9 @@ SEXP R_mongo_client_new(SEXP uri_string, SEXP pem_file, SEXP pem_pwd, SEXP ca_fi
}
*/

return client2r(client);
SEXP c_R = client2r(client);

// add uri as attribute
Rf_setAttrib(c_R, Rf_install("mongoc_uri"), uri_ptr);
return c_R;
}
1 change: 1 addition & 0 deletions src/mongolite.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ SEXP col2r(mongoc_collection_t *col, SEXP prot);
SEXP cursor2r(mongoc_cursor_t* c, SEXP prot);
SEXP client2r(mongoc_client_t *client);
SEXP gridfs2r(mongoc_gridfs_t *fs, SEXP prot);
SEXP uri2r(mongoc_uri_t *uri);
void mongolite_log_handler (mongoc_log_level_t log_level, const char *log_domain, const char *message, void *user_data);
SEXP ConvertObject(bson_iter_t* iter, bson_iter_t* counter);
SEXP bson2list(bson_t *b);
Expand Down
19 changes: 19 additions & 0 deletions src/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@ static void fin_gridfs(SEXP ptr){
R_ClearExternalPtr(ptr);
}

static void fin_uri(SEXP ptr){
#ifdef MONGOLITE_DEBUG
MONGOC_MESSAGE("destroying mongoc uri.");
#endif

if(!R_ExternalPtrAddr(ptr)) return;
mongoc_uri_destroy(R_ExternalPtrAddr(ptr));
R_SetExternalPtrProtected(ptr, R_NilValue);
R_ClearExternalPtr(ptr);
}

SEXP bson2r(bson_t* b){
SEXP ptr = PROTECT(R_MakeExternalPtr(b, R_NilValue, R_NilValue));
R_RegisterCFinalizerEx(ptr, fin_bson, 1);
Expand Down Expand Up @@ -172,6 +183,14 @@ SEXP client2r(mongoc_client_t *client){
return ptr;
}

SEXP uri2r(mongoc_uri_t *uri){
SEXP ptr = PROTECT(R_MakeExternalPtr(uri, R_NilValue, R_NilValue));
R_RegisterCFinalizerEx(ptr, fin_uri, 1);
Rf_setAttrib(ptr, R_ClassSymbol, Rf_mkString("mongo_uri"));
UNPROTECT(1);
return ptr;
}

SEXP R_mongo_collection_disconnect(SEXP ptr){
fin_collection(ptr);
return ptr;
Expand Down

0 comments on commit c58adfe

Please sign in to comment.