[CDRIVER-1070] copy_to_excluding(src, dst, key, ...) appears to be unusable Created: 24/Jan/16  Updated: 03/May/17  Resolved: 24/Jan/16

Status: Closed
Project: C Driver
Component/s: libbson
Affects Version/s: 1.3.1
Fix Version/s: None

Type: Bug Priority: Critical - P2
Reporter: adrian Assignee: A. Jesse Jiryu Davis
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

copy_to_excluding(src, dst, key, ...) cannot be used because of BSON_ASSERT(dst) demands that bson_t *dst = bson_new()
which will then create a memory leak since it malloc a second bson_t.

ie.
bson_t *dst;
copy_to_excluding(src, dst, key, ...) // prints error message
...
bson_destroy(dst);

bson_t *dst = bson_new()
copy_to_excluding(src, dst, key, ...) // no error message but memory leak
...
bson_destroy(dst);

copy_to_excluding_noinit(src, dst, key, ...) is the only possible non-leaking alternative as it doesnt malloc the second bson_t.



 Comments   
Comment by A. Jesse Jiryu Davis [ 24/Jan/16 ]

The BSON_ASSERT serves a purpose. It makes sure you don't copy "src" into a NULL bson_t. bson_copy_to_excluding should be used like:

#include <bson.h>
 
int main()
{
 
   bson_t* src = BCON_NEW ("a", BCON_INT32 (1),
                           "b", BCON_INT32 (2),
                           "c", BCON_INT32 (3),
                           "d", BCON_INT32 (4));
   char *json;
   bson_t dst;
 
   bson_copy_to_excluding (src, &dst, "b", "c", NULL);
   json = bson_as_json (&dst, NULL);
   printf ("%s\n", json);  /* prints { "a" : 1, "d" : 4 } */
 
   bson_free (json);
   bson_destroy (&dst);
   bson_destroy (src);
}

Note that bson_copy_to_excluding is deprecated. Use bson_copy_to_excluding_noinit:

   bson_t dst = BSON_INITIALIZER;
 
   bson_copy_to_excluding_noinit (src, &dst, "b", "c", NULL);

Comment by adrian [ 24/Jan/16 ]

clearly
bson_copy_to_excluding

not
copy_to_excluding

Comment by adrian [ 24/Jan/16 ]

it seems as simple as removing the BSON_ASSERT(dst) and then no error will be raised.

line 214 https://github.com/mongodb/libbson/blob/96731f7926a8480d8f456ee163db6bdf4fecdf9e/src/bson/bson.c

Generated at Wed Feb 07 21:11:28 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.