I'm using the MongoDB C library to insert documents into various collections within the same database and I'm getting the referenced error repeatedly (along with a lovely see fault) when calling BSON_APPEND_OID (doc, "_id", &oid);
I had wanted to use the same oid across collections -- so that each time-stamped entry in each collection would have the same oid, and that's when I started getting the error. So I backed off of that, and tried creating new OIDs for each entry, and I'm still getting the same error.
Version one where I attempt to re-use the OID:
int insert_mongo(char json[100], char *coll, mongoc_client_t *client, bson_oid_t oid){
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
collection = mongoc_client_get_collection (client, "edison", coll);
doc = bson_new_from_json((const uint8_t *)json, -1, &error);
BSON_APPEND_OID (doc, "_id", &oid);
if (!doc) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
return EXIT_SUCCESS;
}
And version 2 where I create a new OID:
int insert_mongo(char json[100], char *coll, mongoc_client_t *client){
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
bson_oid_t oid;
bson_oid_init (&oid, NULL);
collection = mongoc_client_get_collection (client, "edison", coll);
doc = bson_new_from_json((const uint8_t *)json, -1, &error);
BSON_APPEND_OID (doc, "_id", &oid);
if (!doc) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
return EXIT_SUCCESS;
}
Both versions seg fault the SECOND time the function is called with MongoDB bson_append_oid(): precondition failed: bson
I guess that your JSON string does not fit into char[100]
and therefore the segfault is produced at doc = bson_new_from_json((const uint8_t *)json, -1, &error);
. I could imagine that, since you have automatic string length detection enabled (second parameter, -1
), the function continues to read your memory after char[100]
because it cannot find the end of a string that did not fit into the buffer.
To tackle this possibility, replace -1
with 100
(i.e. the size of your buffer) and see if there's an error message instead of a segfault now.
Edit: Expanding on this idea, it could also be that bson_new_from_json
fails, thus doc
is still NULL and in the next line you try to append the OID to NULL, which could produce a segfault.