diff --git a/src/nanoarrow/common/array_stream.c b/src/nanoarrow/common/array_stream.c index 886ea7372..d81009d6b 100644 --- a/src/nanoarrow/common/array_stream.c +++ b/src/nanoarrow/common/array_stream.c @@ -106,7 +106,9 @@ ArrowErrorCode ArrowBasicArrayStreamInit(struct ArrowArrayStream* array_stream, private_data->arrays = (struct ArrowArray*)ArrowMalloc(n_arrays * sizeof(struct ArrowArray)); if (private_data->arrays == NULL) { - ArrowBasicArrayStreamRelease(array_stream); + // array_stream is not initialized yet, so give the schema back to the caller + // as the first allocation failure above does + ArrowSchemaMove(&private_data->schema, schema); ArrowFree(private_data); return ENOMEM; } diff --git a/src/nanoarrow/common/array_stream_test.cc b/src/nanoarrow/common/array_stream_test.cc index 25870b416..7c3426639 100644 --- a/src/nanoarrow/common/array_stream_test.cc +++ b/src/nanoarrow/common/array_stream_test.cc @@ -18,6 +18,8 @@ #include #include +#include + #include "nanoarrow/nanoarrow.hpp" using testing::ElementsAre; @@ -77,6 +79,26 @@ TEST(ArrayStreamTest, ArrayStreamTestEmpty) { ArrowArrayStreamRelease(&array_stream); } +TEST(ArrayStreamTest, ArrayStreamTestInitError) { +#if !defined(__SANITIZE_ADDRESS__) + struct ArrowArrayStream array_stream; + array_stream.release = nullptr; + struct ArrowSchema schema; + + // If the arrays can't be allocated, the caller keeps the schema and the stream is + // left uninitialized + ASSERT_EQ(ArrowSchemaInitFromType(&schema, NANOARROW_TYPE_INT32), NANOARROW_OK); + EXPECT_EQ(ArrowBasicArrayStreamInit( + &array_stream, &schema, + std::numeric_limits::max() / sizeof(struct ArrowArray)), + ENOMEM); + EXPECT_EQ(array_stream.release, nullptr); + ASSERT_NE(schema.release, nullptr); + EXPECT_STREQ(schema.format, "i"); + ArrowSchemaRelease(&schema); +#endif +} + TEST(ArrayStreamTest, ArrayStreamTestIncomplete) { struct ArrowArrayStream array_stream; struct ArrowArray array; diff --git a/src/nanoarrow/nanoarrow.h b/src/nanoarrow/nanoarrow.h index d31d67a81..e0dea0dd1 100644 --- a/src/nanoarrow/nanoarrow.h +++ b/src/nanoarrow/nanoarrow.h @@ -1383,7 +1383,8 @@ static inline void ArrowArrayViewGetDecimalUnsafe(const struct ArrowArrayView* a /// /// This function moves the ownership of schema to the array_stream. If /// this function returns NANOARROW_OK, the caller is responsible for -/// releasing the ArrowArrayStream. +/// releasing the ArrowArrayStream; otherwise, the caller retains ownership +/// of schema. NANOARROW_DLL ArrowErrorCode ArrowBasicArrayStreamInit( struct ArrowArrayStream* array_stream, struct ArrowSchema* schema, int64_t n_arrays);