I have a following code:
bool ok;
bson_t * query = bson_new();
BSON_APPEND_BINARY(query, "_id", BSON_SUBTYPE_BINARY, client_id, CLIENT_ID_SIZE);
bson_t * update = bson_new();
bson_t update_ch1;
BSON_APPEND_DOCUMENT_BEGIN(update, "$set", &update_ch1);
BSON_APPEND_UTF8(&update_ch1, "est", "something");
bson_append_document_end(update, &update_ch1);
bson_t * fields = bson_new();
bson_t reply;
bson_error_t error;
ok = mongoc_collection_find_and_modify(
client_collection,
query,
NULL,
update,
fields,
false, // remove
false, // upsert
false, // new
&reply,
&error
);
if (!ok)
{
fprintf(stderr, "Failed to update client collection in database: %s\n", error.message);
}
bson_destroy(fields);
bson_destroy(update);
bson_destroy(query);
bson_destroy(&reply); <---- Core dump here
The problem is that it occasionally crashes. By analysing a core dump, it has been traced down to a database connectivity issue. In that case, ok
is set to false
and error.message
says "No suitable servers found (serverselectiontryonce
set) ...".
Unfortunately, the code crashed at bson_destroy(&reply);
- obviously reply
bson is not allocated b/c of the error in connection to database. It means that mongoc_collection_find_and_modify() fails to initialise that field in such a situation.
The question is how to reliably detect such a situation and skip bson_destroy()
call.
E.g. (pseudocode):
if (initilized(&reply)) bson_destroy(&reply);