From c16523db218092ba170c5b516b8a87b8ca5fcd28 Mon Sep 17 00:00:00 2001 From: leonarski_f Date: Thu, 16 Apr 2026 08:32:12 +0200 Subject: [PATCH] HDF5Objects: Safer string handling in ReadString() --- writer/HDF5Objects.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/writer/HDF5Objects.cpp b/writer/HDF5Objects.cpp index efecd72c..b0c540e5 100644 --- a/writer/HDF5Objects.cpp +++ b/writer/HDF5Objects.cpp @@ -779,18 +779,24 @@ std::string HDF5DataSet::ReadString() const { HDF5DataSpace file_space(*this); if (file_space.GetNumOfDimensions() != 0) throw JFJochException(JFJochExceptionCategory::HDF5, "Dataset tries to read string (scalar) from vector dataset"); - HDF5DataType file_data_type(*this); - if (file_data_type.GetElemSize() <= 0) + HDF5DataType file_data_type(*this); + const size_t size = file_data_type.GetElemSize(); + + if (size == 0) return ""; - char tmp[file_data_type.GetElemSize()+1]; - tmp[file_data_type.GetElemSize()] = 0; + std::string buffer(size, '\0'); - if (H5Dread(id, file_data_type.GetID(), H5S_ALL, H5S_ALL, H5P_DEFAULT, tmp) < 0) - throw JFJochException(JFJochExceptionCategory::HDF5, dataset_name + ": read unsuccessful"); + if (H5Dread(id, file_data_type.GetID(), H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer.data()) < 0) + throw JFJochException(JFJochExceptionCategory::HDF5, + dataset_name + ": read unsuccessful"); - return {tmp}; + const size_t end = buffer.find('\0'); + if (end != std::string::npos) + buffer.resize(end); + + return buffer; } HDF5DataSet::~HDF5DataSet() {