--- a/tests/test_buffer.c Thu Dec 11 23:07:24 2025 +0100 +++ b/tests/test_buffer.c Thu Dec 11 23:47:46 2025 +0100 @@ -260,13 +260,12 @@ CxBuffer buf; cxBufferInit(&buf, NULL, 16, alloc, CX_BUFFER_FREE_CONTENTS); cxBufferPutString(&buf, "Testing"); - cxBufferTerminate(&buf); CX_TEST_ASSERT(buf.capacity == 16); CX_TEST_ASSERT(buf.size == 7); cxBufferShrink(&buf, 4); CX_TEST_ASSERT(buf.capacity == 11); CX_TEST_ASSERT(buf.size == 7); - CX_TEST_ASSERT(memcmp(buf.space, "Testing", 8) == 0); + CX_TEST_ASSERT(memcmp(buf.space, "Testing", 7) == 0); cxBufferDestroy(&buf); CX_TEST_ASSERT(cx_testing_allocator_verify(&talloc)); } @@ -1174,13 +1173,38 @@ buf.flags |= CX_BUFFER_AUTO_EXTEND; CX_TEST_ASSERT(0 == cxBufferTerminate(&buf)); CX_TEST_ASSERT(buf.size == 8); - CX_TEST_ASSERT(buf.pos == 9); - CX_TEST_ASSERT(buf.capacity > 8); + CX_TEST_ASSERT(buf.pos == 8); + CX_TEST_ASSERT(buf.capacity == 9); CX_TEST_ASSERT(0 == memcmp(buf.space, "preptest\0", 9)); } cxBufferDestroy(&buf); } +CX_TEST(test_buffer_terminate_copy_on_write) { + CxTestingAllocator talloc; + cx_testing_allocator_init(&talloc); + CxAllocator *alloc = &talloc.base; + CxBuffer buf; + cxBufferInit(&buf, "prepAAAAAA\0\0\0\0\0\0", 16, alloc, + CX_BUFFER_COPY_ON_WRITE | CX_BUFFER_DO_NOT_FREE); + buf.capacity = 8; + buf.size = buf.pos = 4; + CX_TEST_DO { + CX_TEST_ASSERT(0 == cxBufferTerminate(&buf)); + CX_TEST_ASSERT(buf.size == 4); + CX_TEST_ASSERT(buf.pos == 4); + CX_TEST_ASSERT(buf.capacity == 5); + CX_TEST_ASSERT(0 == memcmp(buf.space, "prep\0", 5)); + // check if the memory was copied + CX_TEST_ASSERT(cx_testing_allocator_used(&talloc)); + CX_TEST_ASSERT(!cx_testing_allocator_verify(&talloc)); + cxFree(alloc, buf.space); + CX_TEST_ASSERT(cx_testing_allocator_verify(&talloc)); + } + cxBufferDestroy(&buf); + cx_testing_allocator_destroy(&talloc); +} + CX_TEST(test_buffer_write_size_overflow) { CxBuffer buf; cxBufferInit(&buf, NULL, 16, cxDefaultAllocator, CX_BUFFER_DEFAULT); @@ -1471,6 +1495,7 @@ cx_test_register(suite, test_buffer_put_string_copy_on_extend); cx_test_register(suite, test_buffer_put_string_copy_on_write); cx_test_register(suite, test_buffer_terminate); + cx_test_register(suite, test_buffer_terminate_copy_on_write); cx_test_register(suite, test_buffer_write_size_overflow); cx_test_register(suite, test_buffer_write_capacity_overflow); cx_test_register(suite, test_buffer_write_maximum_capacity_exceeded);