Allow GetOutPlace to work with NULL buffers. (#155)
Previously, when used with a NULL buffer at a non-zero offset, the
UsefulOutBuf_GetOutBuf would add the offset to the null pointer and
return it to the caller. The caller would see a non-NULL buffer, but any
attempt to write to it would obviously fail.
This is fixed by returning a NULL buffer if the argument itself is NULL.
diff --git a/inc/qcbor/UsefulBuf.h b/inc/qcbor/UsefulBuf.h
index e7f4d4f..2b85833 100644
--- a/inc/qcbor/UsefulBuf.h
+++ b/inc/qcbor/UsefulBuf.h
@@ -2185,7 +2185,7 @@
UsefulBuf R;
R.len = UsefulOutBuf_RoomLeft(pUOutBuf);
- if(R.len > 0) {
+ if(R.len > 0 && pUOutBuf->UB.ptr != NULL) {
R.ptr = (uint8_t *)pUOutBuf->UB.ptr + pUOutBuf->data_len;
} else {
R.ptr = NULL;
diff --git a/test/UsefulBuf_Tests.c b/test/UsefulBuf_Tests.c
index 3ab3557..e729ff1 100644
--- a/test/UsefulBuf_Tests.c
+++ b/test/UsefulBuf_Tests.c
@@ -35,7 +35,7 @@
/* This calls the main methods to add stuff to a UsefulOutBuf.
- * The result in the UsefulOutBuf is "heffalump unbounce bluster hunny"
+ * The result in the UsefulOutBuf is "heffalump unbounce bluster hunny bear"
*/
const char *AddStuffToUOB(UsefulOutBuf *pUOB)
{
@@ -57,8 +57,8 @@
/* add a space to end */
UsefulOutBuf_AppendByte(pUOB, ' ');
- /* Add 5 bytes to the end */
- UsefulBufC UBC = {"hunny", 5};
+ /* Add 6 bytes to the end */
+ UsefulBufC UBC = {"hunny ", 6};
UsefulOutBuf_AppendUsefulBuf(pUOB, UBC);
/* Insert 9 bytes at the beginning, slide the previous stuff right */
@@ -69,6 +69,13 @@
UsefulBufC UBC2 = {"unbounce ", 9};
UsefulOutBuf_InsertUsefulBuf(pUOB, UBC2, 10);
+ /* Add 4 bytes to the end, by accessing the buffer directly and then advancing it */
+ UsefulBuf UB = UsefulOutBuf_GetOutPlace(pUOB);
+ if (!UsefulBuf_IsNULL(UB)) {
+ memcpy(UB.ptr, "bear", UB.len < 4 ? UB.len : 4);
+ }
+ UsefulOutBuf_Advance(pUOB, 4);
+
Done:
return szReturn;
}
@@ -97,7 +104,7 @@
goto Done;
}
- const UsefulBufC Expected = UsefulBuf_FROM_SZ_LITERAL("heffalump unbounce bluster hunny");
+ const UsefulBufC Expected = UsefulBuf_FROM_SZ_LITERAL("heffalump unbounce bluster hunny bear");
UsefulBufC U = UsefulOutBuf_OutUBuf(&UOB);
if(UsefulBuf_IsNULLC(U) ||