From 85a52470f95a8236af0d1f12400c5bad7be5e16d Mon Sep 17 00:00:00 2001 From: Daniel Markstedt Date: Tue, 4 Aug 2026 23:41:23 +0200 Subject: [PATCH] allow NULL empty blocks in blk2bstr Treat a NULL source pointer as valid when len is zero, since no source memory is read and the result is an ordinary empty bstring. Keep negative lengths and NULL pointers paired with a positive length as errors. Document the contract in the public header, and cover the accepted form with the core unit test. Thanks to @DamjanJovanovic for the report --- bstring/bstrlib.c | 2 +- bstring/bstrlib.h | 3 +++ tests/bstest.c | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/bstring/bstrlib.c b/bstring/bstrlib.c index 2676304..58d587c 100644 --- a/bstring/bstrlib.c +++ b/bstring/bstrlib.c @@ -273,7 +273,7 @@ blk2bstr(const void *blk, int len) { bstring b; int i; - if (blk == NULL || len < 0) { + if (len < 0 || (len > 0 && blk == NULL)) { return NULL; } b = malloc(sizeof(struct tagbstring)); diff --git a/bstring/bstrlib.h b/bstring/bstrlib.h index ce00808..2cc97a3 100644 --- a/bstring/bstrlib.h +++ b/bstring/bstrlib.h @@ -147,6 +147,9 @@ bfromcstrrangealloc(int minl, int maxl, const char *str); * Create a bstring whose contents are described by the contiguous buffer * pointing to by blk with a length of len bytes. * + * If len is zero, blk may be NULL. Otherwise, blk must point to at least len + * bytes. + * * Note that this function creates a copy of the data in blk, rather than * simply referencing it. Compare with the blk2tbstr macro. If an error * occurs NULL is returned. diff --git a/tests/bstest.c b/tests/bstest.c index 8fb38a2..383ee5b 100644 --- a/tests/bstest.c +++ b/tests/bstest.c @@ -200,7 +200,7 @@ START_TEST(core_001) { /* tests with NULL */ test1_0(NULL, 10, NULL); - test1_0(NULL, 0, NULL); + test1_0(NULL, 0, ""); test1_0(NULL, -1, NULL); /* normal operation tests */ test1_0(SHORT_STRING, sizeof(SHORT_STRING) - 1, SHORT_STRING);