[CDRIVER-1579] bson_malloc needs same count test as bson_malloc0 Created: 04/Oct/16  Updated: 12/Jan/17  Resolved: 05/Oct/16

Status: Closed
Project: C Driver
Component/s: libbson
Affects Version/s: 1.4.2
Fix Version/s: 1.5.0

Type: Bug Priority: Major - P3
Reporter: Tom Schmidt Assignee: Hannes Magnusson
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

C++ Builder 10.1 Berlin


Backwards Compatibility: Fully Compatible

 Description   

bson_malloc() aborts on a zero length malloc.

Compilers aren't required to return a ptr for 0 length, they may return NULL instead. Solution is to use same test as used in bson_malloc0 (somebody appears to have looked into this previously but it didn't get applied to bson_malloc).

This is relevant because there is code in the mongodb c driver that expects to get a valid pointer on a 0 length call to malloc (mongoc_set_for_each() is one example). On a susceptible compiler you can't even get past mongoc_client_new() without the patch applied.

Corrected version:

void *
bson_malloc (size_t num_bytes) /* IN */
{
   void *mem = NULL;
 
   if (BSON_LIKELY (num_bytes)) {
      if (BSON_UNLIKELY (!(mem = gMemVtable.malloc (num_bytes)))) {
         abort ();
      }
   }
 
   return mem;
}



 Comments   
Comment by Hannes Magnusson [ 05/Oct/16 ]

Fixed in master (to become 1.5.0):

https://github.com/mongodb/libbson/commit/8c49facbc86ec8155401c7382dc0f459b9c08532

I find it unlikely that we will be releasing 1.4.3, but if we do, I'll keep this ticket in mind.

Comment by Hannes Magnusson [ 04/Oct/16 ]

malloc(3):

If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

Thanks for the report.

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